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
?