我正在尝试编写authGuard
。这是我的代码:
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.auth.user.pipe(
map(user => {
if (user) {
console.log('ok');
return true;
} else {
console.log('denied');
this.router.navigate(['/login']);
return false;
}
})
);
}
}
在我的authService
中,我有一个用户:Observable<User>;
。
问题是,authGuard
仅在加载用户时检查一次,无论是否为null。当防护措施返回true并允许访问该页面时,一旦用户更改它就不会更新。因此,当我注销并且用户oberservable
为空时,防护措施应返回false并重定向到登录页面,但这不起作用。
所以我可以让pipe
听其observable
的变化吗?