簡體   English   中英

如何使用Firebase的onAuthStateChanged來跟蹤Angular中的用戶登錄狀態?

[英]How to use Firebase's onAuthStateChanged to track user login state in 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');
      } 
    });
  }
}

但是當onAuthStateChanged時,我收到一條錯誤,指出this.router未定義。

我意識到問題是匿名函數的范圍問題。 使用=>語法修復了問題。

@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');
      } 
    });
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM