2017-03-04 18 views
1

角度2のアプリでFirebaseデータベースからuidで1レコードを取得しようとしています。問題は、私は常にプロファイル変数のundefiniedを得ているということです。これを行う正しい方法を私に教えてください。ありがとう! 私のコードは:ファイヤーベースから角度2のレコードを取得する方法

プロファイルクラス

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); 
    } 
} 

プロファイルサービス

@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)); 
関連する問題