Introduction
I'm trying to create a route guard in Angular2+
using Observable from the shared service which holds the string value of current user role.
The problem is obviously in shifting my mind from Promises to Observables.
What I made so far is based on heuristics and try & error approach but I hit the wall by killing the browser Solved thanks to danday74
.
Attempt (improved thanks to @danday74)
With the help of RxJS sequence equvalent to promise.then()? i've translated what i want to do into this chain:
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> | boolean {
return this.auth.isRoleAuthenticated(route.data.roles)
.mergeMap((isRoleAuthenticated: boolean) => {
return isRoleAuthenticated ? Observable.of(true) : this.auth.isRole(Roles.DEFAULT_USER);
})
.do((isDefaultUser: boolean) => {
const redirectUrl: string = isDefaultUser ? 'SOMEWHERE' : 'SOMEWHERE_ELSE';
this.router.navigate([redirectUrl]);
})
.map((isDefaultUser: boolean) => {
return false;
});
}
Question
How to stop further propagation of observable chain if isRoleAuthenticated = true
? I need to return that boolean value if such condition is met and make sure .do
operator block is not called after.
Limitation is that boolean value must be returned from canActivate
guard.
setTimeout()
andtake(1)
, still i can't debug and browser loads forever until the page becomes unresponsive. – Scorcher