如何使用 Firebase 的 onAuthStateChanged 来跟踪 Angular 中的用户登录状态?

pdi*_*ley 4 javascript firebase firebase-authentication angular

我已经使用 Firebase 设置了用户登录流程,现在正在尝试保护页面在用户未登录时不被访问。从Firebase 文档中,我知道我可以使用 跟踪用户登录状态onAuthStateChanged,但我不能确定该函数中应包含哪些内容,以便我能够识别用户是否从路由防护登录。如何使用 跟踪登录状态onAuthStateChanged

编辑:

更具体地说,我不确定在onAuthStateChanged被调用时如何引导路由器。我尝试调用注入的路由器

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  constructor(
    private afAuth: AngularFireAuth,
    private router: Router,
  ) {
    this.afAuth.auth.onAuthStateChanged(function(user) {
      if (user) {
        this.router.navigate('home');
      } else {
        this.router.navigate('login');
      } 
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

但是当onAuthStateChanged调用时,我收到一条错误,指出this.router未定义。

pdi*_*ley 7

我意识到问题是匿名函数的范围问题。使用=>语法可以解决问题。

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  constructor(
    private afAuth: AngularFireAuth,
    private router: Router,
  ) {
    this.afAuth.auth.onAuthStateChanged((user) => {
      if (user) {
        this.router.navigate('home');
      } else {
        this.router.navigate('login');
      } 
    });
  }
}
Run Code Online (Sandbox Code Playgroud)