如何在 Angular 2 中从 firebase 获取一条记录

How to get one record from firebase in Angular 2

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

简介class

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

结果是一个数组,您可能希望将第一个值和 return 作为 Observable

.first emits only the first value (or the first value that meets some condition) emitted by the source Observable.

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