从ReplaySubject< boolean>获取布尔值可观察的 [英] Getting boolean value from ReplaySubject<boolean> asObservable

查看:112
本文介绍了从ReplaySubject< boolean>获取布尔值可观察的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注Angular2的thinkster教程,并做了这两部分来检查用户是否已通过身份验证:

I'm following thinkster tutorial for Angular2, and I made these two for checking if the user is authenticated:

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

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

now, in my auth-gaurd.service.ts, I want to check the boolean value of isAuthenticated. How can I do that? I want to do something like this:

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的此处

You can find the complete code from thinkster here

推荐答案

Günter在评论中提到,我通过订阅 isAuthenticated 来解决.代码应如下所示:

As Günter mentioned in the comments, I solved it by subscribing to the isAuthenticated. The code should be like this:

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

这篇关于从ReplaySubject&lt; boolean&gt;获取布尔值可观察的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆