this question is somehow related to this questions 1,2 , but they do not addressed the subject of synchronous observables in javascript in a manner that can help me.
I'm currently in angular 4 or just angular and i have a protected route waiting for two guards to resolve. the two of them returns true as expected but the second one takes too long so it's answer comes after the canActivate method has finished. example code below. what can i do to wait for my second guard to synchronously resolved?
I'm new to this javascript and observables async way of doing things! Sorry if this question is silly.
first authGuard:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if(this.cookieService.check('token'))return true; console.log(true); //For demostration purpose }
second authGuard:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { this.roleService.checkRole('admin') // this service take some time .subscribe( response=>{ //Simple logic checking the response. console.log(true); return true; }, error=>{ //some logic with the error console.log(false); return false; } ) console.log('End of authguard method'); }
roleService:
checkRole(role:string): boolean { return this.http.post(Url, body,requestOptions) .map(this.processData) .catch(this.handleError); }
4.Console shows:
true // from authGuard 1
"End of authguard method" // from authGuard 2
true // from authGuard 2
The router can not navigate to the desire route because of the second true coming too late. I also have tried the first()
operator before subscribing and the first operator do not wait for the observable in the role.Service to resolve.