【问题标题】:Getting boolean value from ReplaySubject<boolean> asObservable从 ReplaySubject<boolean> asObservable 获取布尔值
【发布时间】: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 做到了

标签: angular authentication


【解决方案1】:

正如 cmets 中提到的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);
}

【讨论】:

    猜你喜欢
    • 2019-02-08
    • 1970-01-01
    • 2016-07-08
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 2012-05-19
    • 1970-01-01
    相关资源
    最近更新 更多