注销时无法读取 null 的 属性 'uid'

Cannot read property 'uid' of null when logout

每次我从我的应用程序注销时,我都会得到

Cannot read property 'uid' of null

来自控制台。它导致引用以下代码:

constructor( private firestore: AngularFirestore, private auth: AuthService, ) 
{
firebase.auth().onAuthStateChanged(user => {
  if (this.currentUser == user) {
    this.currentUser = firebase.auth().currentUser;
    this.vendor = firebase.firestore().doc(`/Products/${this.currentUser.uid}`);
  }
});

只要用户的身份验证状态发生变化,就会触发 onAuthStateChanged 回调,因此只要他们登录或注销。在后一种情况下,user 将是 null,您现在在代码中没有正确处理它。

这看起来更正确:

firebase.auth().onAuthStateChanged(user => {
  this.currentUser = firebase.auth().currentUser;
  if (this.currentUser) {
    this.vendor = firebase.firestore().doc(`/Products/${this.currentUser.uid}`);
  }
});

您可以使用 uid 进行可选链接

firebase.firestore().doc(`/Products/${this.currentUser?.uid}`)

或另一种解决方案是当您从系统注销时设置当前用户为 null 或空对象

setCurrentUser({})