2017-03-04 65 views
1

我想通过Angular 2应用程序中的我的Firebase数据库中的uid获取一条记录。问题是我总是在配置文件变量中获得undefinied。你能告诉我正确的方法吗?谢谢! 我的代码:如何从Angular 2中的Firebase数据库中获取一条记录

Profile类

export class Profile{ 
    constructor(public $key:string, public userId:string, public description:string, public avatarUrl: string){ 
    } 

    static parseFromJson({$key, userId, description, avatarUrl}):Profile{ 
     return new Profile($key, userId, description, avatarUrl); 
    } 
} 

Profiles服务

@Injectable() 
export class ProfilesService { 
    constructor(private db: AngularFireDatabase) { 
    } 

    getUserByUserId(userId:string): Observable<Profile>{ 
    return this.db.list('profiles',{ 
     query: { 
      orderByChild: 'userId', 
      equalTo: userId 
     } 
    }).map(result => Profile.parseFromJson(result[0])); 
    } 
} 

轮廓组件

export class ProfileComponent { 

    profile: Profile; 
    uid: string; 

    constructor(private profileService: ProfilesService, private af: AngularFire) { 
    this.af.auth.subscribe(auth => this.uid = auth.uid); 
    this.profileService.getUserByUserId(this.uid).subscribe(
     result => { 
      this.profile = result; 
     } 
    ); 
    } 
} 

回答

2

结果是一个数组,你可能要采取的第一个值和返回为Observable

.first只发出源Observable发出的第一个值(或符合某些条件的第一个值)。

getUserByUserId(userId:string): Observable<Profile>{ 
    return this.db.list('profiles',{ 
     query: { 
      orderByChild: 'userId', 
      equalTo: userId 
     } 
    }) 
    .first() 
    .map(result => Profile.parseFromJson(result)); 
相关问题