从ReplaySubject <boolean> asObservable获取布尔值

时间:2017-03-09 09:42:21

标签: angular authentication

我正在关注Angular2的thinkster教程,我将这两个用于检查用户是否经过身份验证:

private isAuthenticatedSubject = new ReplaySubject<boolean>(1);
public isAuthenticated = this.isAuthenticatedSubject.asObservable();

现在,在我的auth-gaurd.service.ts中,我想检查 isAuthenticated 布尔值。我怎样才能做到这一点?我想做这样的事情:

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);
}

您可以从thinkster here

中找到完整的代码

1 个答案:

答案 0 :(得分:1)

在评论中提及Günter时,我通过订阅 isAuthenticated 解决了这个问题。代码应该是这样的:

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
): Observable<boolean> {

    var isAuthenticated = false;

    // Check if the user is authenticated
    this.userService.isAuthenticated.take(1).subscribe(function (data) {
        isAuthenticated = data;
    });

    // If the user is not authenticated, redirect to Login page
    if (!isAuthenticated) {
        this.router.navigateByUrl('/login');
    }

    return this.userService.isAuthenticated.take(1);
}