[英]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.