我在 Angular 应用中有两个非常相似的守卫。首先检查的是用户登录:
// isUser guard
export class isUser implements CanActivate {
constructor(
private fireAuth: AngularFireAuth,
private router: Router
) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.fireAuth.authState.pipe(
take(1),
map(authState => !!authState),
tap(auth => !auth ? this.router.navigate(['/']) : true)
)
}
}
这一项工作正常:当用户未登录时,不允许他打开受保护的页面。
下一个守卫几乎相同,但它检查用户是否未登录:
export class isGuest implements CanActivate {
constructor(
private fireAuth: AngularFireAuth,
private router: Router
) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.fireAuth.authState.pipe(
take(1),
map(authState => !!authState),
tap(auth => auth ? this.router.navigate(['/']) : true)
)
}
}
唯一的区别是:!auth ? this.router.navigate(['/'])
vs auth ? this.router.navigate(['/'])
。
但是isUser
守卫工作得很好,并且isGuest
总是允许用户页面。我做错了什么,为什么它不能工作?