Angular Firebase ng如果用户经过身份验证,则侦听器在页面重新加载时不起作用



我使用onAuthStateChanged from firebase来侦听用户的身份验证状态。我正在侦听导航组件中的这些更改,以决定是否显示登录按钮或注销按钮等。

如果我在应用程序中导航,这工作得很好,但当我刷新页面时,DOM反映用户的状态,即使订阅被触发。

可能是一个简单的修复,我忽略了,但我还没有能够找到一个修复,在我的研究工作,并投入了太多的时间在它-_-请帮助!

这是我的authService:

private authStatusSub = new Subject();
user$ = this.authStatusSub.asObservable();
setAuthStatusListener() {
this.auth.onAuthStateChanged((user) => {
if (user) {
this.usersService
.getUserData(user.uid)
.then((userData) => {
this.authStatusSub.next(userData);
})
.catch((err) => {
console.log(err);
});
} else {
this.authStatusSub.next(null);
console.log('User has logged out');
}
});
}

导航类型文件:

isAuthenticated: boolean;
ngOnInit() {
this.authService.setAuthStatusListener();
this.authService.user$.subscribe((userData) => {
if (userData) {
this.isAuthenticated = true;
console.log(userData);
} else {
this.isAuthenticated = false;
}
});
}

导航html:

<a routerLink="/login" *ngIf="!isAuthenticated" mat-button class="navButton">Login</a>
<a mat-button *ngIf="isAuthenticated" class="navButton" (click)="onLogout()">Logout</a>

当我通过正常的应用程序流程登录、注销并导航到主页(导航栏所在的位置)时,它按预期工作,但是当我刷新主页(导航栏所在的位置)时,状态没有反映在DOM中。即使状态没有被反映,nav typescript文件中的console.log()也会用正确的数据触发,所以我知道这个可观察对象正在工作。

将非常感谢任何帮助!!

由于您使用的是AngularFireAuth,您可以这样简化您的服务:

服务:

  • 摆脱受试者(authStatusSub)
  • 直接从AngularFireAuth.authState定义user$
  • 不要订阅服务!

代码可以是这样的:

服务:

constructor(private fireAuth: AngularFireAuth) { }
user$ = this.fireAuth.authState;

导航组件:

this.authService.user$.subscribe(
userData => this.isAuthenticated = !!userData
);

最新更新