【问题标题】:Uid null when calling getProfile method调用getProfile方法时uid为空
【发布时间】:2018-08-29 11:52:04
【问题描述】:

在初始化我的应用程序时,我调用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 而不会出错?

【问题讨论】:

    标签: angular typescript firebase firebase-authentication


    【解决方案1】:

    请使用switchMap,以便您可以等待。

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

    【讨论】:

    • 如何使用它?我正在按照您上面描述的方式运行,但显示错误:ERROR TypeError: this.afAuth.authState.flatMapLatest is not a function
    • 哎呀,已经改名了,你可以试试switchMap吗?如果它仍然不起作用,请在文件顶部添加import 'rxjs/add/operator/switchMap'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2021-09-07
    相关资源
    最近更新 更多