canLoad does not work with BehaviorSubject

0

The AuthenticationManager service has the following code:

private loggedIn: BehaviorSubject<boolean>;

constructor(
     private http: ApplicationHttpClient, 
     private router: Router, private a: HttpClient) 
{
    this.loggedIn = new BehaviorSubject<boolean>(false);
}

isLoggedIn():Observable<boolean> {
    return this.loggedIn.asObservable();
}

initSession():void {
   this.getUserSession().subscribe(
     response => {
       this.loggedIn.next(true);
     }
   );
}

getUserSession():Observable<any> {
    return this.a.get('http://localhost/api/v1/usersession', {});
}

The initSession method is called by app.component.ts to query the API and get the user's session.

The route has canLoad configured:

//...
canLoad: [AccessManagerGuard]
//...

The AccessManagerGuard has the following code:

canLoad(route: Route): Observable<boolean>|Promise<boolean>|boolean {
    return this.AuthenticationManager.isLoggedIn()
      .map((isLoggedIn: boolean) => {
         if (!isLoggedIn)
           return false;
         return true;
      });
}

Notice that canLoad executes isLoggedIn which in turn returns a Observable .

isLoggedIn():Observable<boolean> {
    return this.loggedIn.asObservable();
}

In this way canLoad does not work since the loggedIn variable starts with the value false .

I realize that the isLoggedIn method immediately returns the value false but I need to wait for the result of the getUserSession method.

How do I get the isLoggedIn method to wait for the getUserSession ?     

asked by anonymous 07.02.2018 / 11:28

1 answer

0

The solution was to change BehaviorSubject to AsyncSubject in AuthenticationManagerService service:

private loggedIn: AsyncSubject<boolean> = new AsyncSubject();
//...
isLoggedIn():Observable<boolean> {
    return this.loggedIn;
}

initSession():void {
    this.getUserSession().subscribe(
        response => {
            this.loggedIn.next(true);
            this.loggedIn.complete();
        }
    );
}
//...

Seetheimageabove,thelasteventwillonlybeissuedaftercomplete,soitispossibletocreateaneventwiththenextandthedesiredvalue,whichinmycasecouldonlybeissuedaftertheconclusionoftheGETREQUEST.

Source: link

    
07.02.2018 / 15:11