CanActivate 的行为与 Angular 7 与 firebase 的行为不符
CanActivate is not behaving as it should with Angular 7 with firebase
在我的 Authservice
中,我有:
getAuthenticationState(): Observable<any> {
return this.angularFireAuth.authState;
}
在我的 Guard
中:
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
// In case of refresh
return this.authService.getAuthenticationState()
.pipe(map(user => !!user))
.pipe(tap(loggedIn => {
console.log(loggedIn);
if (!loggedIn) {
this.router.navigate(['/admin/login']);
} else {
return true;
}
}));
}
我的问题是我必须点击登录按钮两次(我确定它是按预期实现的),看来 Guard 没有作为可观察到,loggedIn 值只打印一次。
添加 take(1) 来解决它以及为什么使用 2 个管道,将其更改为
return this.authService.getAuthenticationState()
.take(1)
.pipe(
map(user => !!user),
tap(loggedIn => {
console.log(loggedIn);
if (!loggedIn) {
this.router.navigate(['/admin/login']);
} else {
return true;
}
})
);
在我的 Authservice
中,我有:
getAuthenticationState(): Observable<any> {
return this.angularFireAuth.authState;
}
在我的 Guard
中:
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
// In case of refresh
return this.authService.getAuthenticationState()
.pipe(map(user => !!user))
.pipe(tap(loggedIn => {
console.log(loggedIn);
if (!loggedIn) {
this.router.navigate(['/admin/login']);
} else {
return true;
}
}));
}
我的问题是我必须点击登录按钮两次(我确定它是按预期实现的),看来 Guard 没有作为可观察到,loggedIn 值只打印一次。
添加 take(1) 来解决它以及为什么使用 2 个管道,将其更改为
return this.authService.getAuthenticationState()
.take(1)
.pipe(
map(user => !!user),
tap(loggedIn => {
console.log(loggedIn);
if (!loggedIn) {
this.router.navigate(['/admin/login']);
} else {
return true;
}
})
);