canLoad does not work with Behaviorsubject

Asked

Viewed 53 times

0

The service AuthenticationManager 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 method initSession is called by app.component.ts to view the API and get the user session.

The route possesses the 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;
      });
}

Note that the canLoad executes the isLoggedIn which in turn returns a Observable.

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

Thus the canLoad does not work, since the variable loggedIn is started with the value false.

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

How do I make the method isLoggedIn wait for method response getUserSession?

1 answer

0

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

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();
        }
    );
}
//...

inserir a descrição da imagem aqui

See the image above, the last event will only be issued after the complete, so it is possible to create an event with the next and the desired amount, which in my case could only be issued after the completion of GET REQUEST.

Source: https://medium.com/front-end-hacking/creating-an-observable-with-angular-part-ii-the-4-different-types-3d8fd2835850

Browser other questions tagged

You are not signed in. Login or sign up in order to post.