调用getProfile方法时,Uid为null

时间:2018-03-20 15:20:44

标签: angular typescript firebase firebase-authentication

初始化我的应用程序时,我调用getProfile ()方法返回用户个人资料信息并显示在屏幕上。

但无论何时初始化,都会发生以下错误:

ERROR TypeError: Can not read property 'uid' of null

auth.service.ts:

  authState: any = null;

  this.afAuth.authState.subscribe((auth) => {
     this.authState = auth;
  });

  getProfile() {
    // error occurs when you try to access this.authState.uid but subscribe 
    // has not yet completed

    return this.afs.collection(`${this.authState.uid}`).doc('perfil-usuario')
      .snapshotChanges()
      .map(p => {
        return { ...p.payload.data() };
      });
  }

有没有办法在每次访问displayName,photoURL或UID等值时输入authState,没有错误?

1 个答案:

答案 0 :(得分:0)

使用switchMap,等待它。

 getProfile() {
    return this.afAuth.authState
        .switchMap(({uid}) =>
            this.afs
                .collection(`${uid}`)
                .doc('perfil-usuario')
                .snapshotChanges()
                .map(p => ({...p.payload.data()}))
         )
  }