Angular/fire authState.subscribe 不响应注销

Angular/fire authState.subscribe not respond to logout

我是 angular 的新手,我正在尝试使用 firebase 进行身份验证。我已经构建了 login/register 并注销了。它现在工作正常,但现在我想显示一个导航栏(一个完全独立的组件),它有一个登录按钮和注销按钮。我需要根据用户的 authState 切换这些按钮。所以我在 authState 上使用了订阅。但它只在用户登录时起作用。它不会在用户注销时触发。当用户注销时它应该 return null 对吗?我检查了 authService 里面的 authState,用户注销后它是空的。那么我在这里做错了什么?

这是我的代码。

auth.service.ts

    import { Injectable } from '@angular/core';
    import { AngularFirestore } from '@angular/fire/firestore';
    import { AngularFireAuth } from '@angular/fire/auth';
    import { Observable, of } from 'rxjs';
    import * as firebase from 'firebase/app';
    
    @Injectable({
      providedIn: 'root'
    })
    
    export class AuthService {
      authState: any;
    
      constructor(
        public db: AngularFirestore,
        public mAuth: AngularFireAuth
      ) {}
    
      getAuthState() {
        return this.mAuth.authState;
      }
      doLogout() {
        return new Promise((resolve, reject) => {
          if (firebase.auth().currentUser) {
            this.mAuth.auth.signOut();
            resolve();
          } else {
            reject();
          }
        });
      }

    /* login, register, etc... */

    }

nav.component.ts

    import { Component, OnInit } from '@angular/core';
    import { AuthService } from 'src/app/auth/auth.service';
    import { Router } from '@angular/router';
    import * as firebase from 'firebase/app';
    
    @Component({
      selector: 'app-navbar',
      templateUrl: './navbar.component.html',
      styleUrls: ['./navbar.component.scss']
    })
    export class NavbarComponent implements OnInit {
    
      user: any;
    
      constructor(
        private authService: AuthService,
        private router: Router) {}
    
      ngOnInit() {
        this.authService.getAuthState().subscribe( user => {
          /* this doesn't respond to logout ... */
          console.log(user);
          this.user = user;
        });
      }
      tryLogout() {
        this.authService.doLogout()
          .then(res => {
            console.log('tryLogout', res);
            this.router.navigate(['/login']);
          }, err => console.log(err));
      }
    }

我很确定您的 authService doLogout() 正在返回一个承诺的承诺。

auth.signout() 已经 returns 一个承诺。

我认为您的 doLogout() 函数应该是:

return this.mAuth.auth.signout()

旁注:我 运行 遇到了这个完全相同的问题,这是因为 authstate 在某种程度上受到了 router.navigate 的影响。我的错误是:

this.authstate.signout();
this.router.navigate(['/']);

但是使用上面的代码,authstate 永远不会真正改变。解决问题的方法是:

this.authstate.signout().then(this.router.navigate(['/'])

有区别:

authState.subscribe((user: any) => {
  if (user) {
    // logged in
  }
});

onAuthStateChanged((user: any) => {
  if (user) {
    // logged in
  }
});

因为后者将 return 注销后的正确状态...