Getting boolean value from ReplaySubject

2019-09-07 03:48发布

问题:

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

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

You can find the complete code from thinkster here

回答1:

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