【发布时间】:2017-03-09 09:42:21
【问题描述】:
我正在关注 Angular2 的 thinkster 教程,我制作了这两个用于检查用户是否经过身份验证:
private isAuthenticatedSubject = new ReplaySubject<boolean>(1);
public isAuthenticated = this.isAuthenticatedSubject.asObservable();
现在,在我的 auth-gaurd.service.ts 中,我想检查 isAuthenticated 的 boolean 值。我怎样才能做到这一点?我想做这样的事情:
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
//THIS IS NOT WORKING!
//Operator '===' cannot be applied to types 'Observable<boolean>' and 'boolean'
if (this.userService.isAuthenticated.take(1) === false) {
this.router.navigateByUrl('/login');
}
return this.userService.isAuthenticated.take(1);
}
你可以从thinksterhere找到完整的代码
【问题讨论】:
-
@GünterZöchbauer,问题是 1)我使用 ReplaySubject 而不是 BehaviorSubject 因为我可以在没有初始值的情况下创建 isAuthenticatedSubject 2)我想使用 isAuthenticated
-
我没有检查过
ReplaySubject,也许它和BehaviorSubject一样。你试过了吗? -
也许你可以让它共享,订阅它并将值存储在订阅的属性中。
-
@GünterZöchbauer,谢谢,我通过订阅 isAuthenticated 做到了