注销用户后抛出 AngularFire2 错误

AngularFire2 error thrown after signing out the user

我正在使用 Angularfire2 库登录用户并从 Firebase 数据库中获取数据,但是当用户点击注销时,控制台会抛出以下错误:

Cannot read property 'uid' of null at line

这里是 uid 属性 在任务组件的 ngOnInit 方法的第 2 行抛出错误:

ngOnInit() {
    this.authSub1 = this.auth.authState.subscribe((auth) => {
        this.tasksSub = this.af.list(`users/${auth.uid}/tasks`, { preserveSnapshot: true }).subscribe(snapshots => {
            snapshots.forEach(snapshot => {
                this.tasksArray.push(snapshot.val().name);
            });
        });
    }, (err) => {this.openSnackBar(); console.log(err); });
}

然后我在上面的订阅上调用 unsbuscribe 以避免 ngOnDestroy 方法中的内存泄漏:

ngOnDestroy() {
    this.authSub1.unsubscribe();
}

这是主组件上的按钮触发的注销方法(主组件的路由器出口显示上述组件):

logout() {
    this.auth.auth.signOut()
    .then(() => { 
        this.router.navigateByUrl('/login'); 
    })
    .catch(function(err) {console.log(err); });
}

找到了!解决方案非常简单:

为了避免在用户点击注销时用户 ID 为 null 我只需要避免使用 authState.subscribe 回调参数中的 uid 并只使用一个新创建的变量来代替存储uid 直接来自 ngOnInit:

上注入的 AngularFireAuth 服务
this.userId = this.auth.auth.currentUser.uid;