I guess this might more of a rxjs understanding topic but the context illustrates my want of it the best :)
So below it the working code inside my PageGuard class, which prevents routing to pages unless a valid jwt exists in localStorage.
CheckForToken() just appends Authorization Header if token exists in localStorage.
public isAuthenticated():Observable<boolean>{
this.checkForToken();
let isAuth = new Observable<boolean>(observer => {
this.http.get(`https://testhan-api.selfbits.io/api/v1/user`,{headers: this.headers}).subscribe(res => {
if (res.status === 200){
observer.next(true);
observer.complete();
}else{
observer.next(false);
observer.complete()
}
},err => console.log(err));
});
return isAuth
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.isAuthenticated()
}
and the routing path looks like this
{
path:'dashboard',
component:DashboardComponent,
canActivate:PageGuard
}
My question: So far, my understanding is that you need to subscribe to an observable, in order to execute it, like
observable.subscribe(res => //do something with res)
but here I'm only returning an observable, it doesn't get subscribed, but how does the guard evaluate it?
thanks for the clarification!