首页 > 解决方案 > 无法读取 null 的“uid”的属性

问题描述

我需要帮助,我使用 firebase 作为后端,使用 Ionic 4 作为前端。

我在控制台上出现错误,当我第一次打开/启动应用程序时,我收到无法读取控制台上的 null 'uid' 属性。

我阅读了一些相关的解决方案,但我还没有找到解决我的问题的解决方案。

以下是我在我的应用程序中实现它时的代码:

initializeApp() {

this.afAuth.auth.onAuthStateChanged(user => {
  const userId = user.uid;
  this.db.doc(`accounts/${userId}`).valueChanges().pipe(
    take(1)
  ).subscribe(userData => {
    const role = userData['role'];
    if (role == 'USER') {
      console.log('we got a customer user');
      this.router.navigateByUrl('/tabs/home')
    } else if (role == 'VENDOR') {
      console.log('we got a seller user');
      this.router.navigateByUrl('/vendor-tabs/home-vendor')
    }
  })
})
}

标签: google-cloud-firestorefirebase-authenticationionic4

解决方案


当用户登录和注销时,调用身份验证状态更改侦听器。user如果未登录,将为 null。这意味着您必须user在开始访问其属性之前检查是否为真。

this.afAuth.auth.onAuthStateChanged(user => {
  if (user) {
    // user is signed in
    const userId = user.uid;
  }
  else {
    // user is signed out - can't use properties of user.
  }
}

请参阅API 文档


推荐阅读