Angular2 - returns a boolean value with a canActivate subscription

I am new to Angular, I need to implement a function that returns true / false, I will use return in canActivate guard, but this function consumes api via http.get, so the message is asynchronous, this function always returns FALSE, because http.get not yet running.

My cool guard:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { let url: string = state.url; if (this.loginService.isLoggedIn()) { return true; } this.loginService.redirectUrl = url; this.router.navigate(['login']); return false; } 

and isLoggedIn () function

 isLoggedIn() { let logged: boolean = false; this.http.get('api/values', this.httpService.headers()) .map((res: Response) => { logged = res.json(); }); return logged; } 

I read a lot of questions, but could not find an answer.

+6
source share
1 answer

Typical guards say he can return

 Observable<boolean>, Promise<boolean> or boolean 

so change isLoggedIn to:

 isLoggedIn() { return this.http.get('api/values', this.httpService.headers()) .take(1) .map((res: Response) => res.json()); } 

Update

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { let url: string = state.url; return this.isLoggedIn().map(loggedIn => { if(!loggedIn) { this.loginService.redirectUrl = url; this.router.navigate(['login']); } return loggedIn; } } 
+7
source

All Articles