Angular2 - return boolean with subscribe to canActivate

Rit picture Rit · Sep 29, 2016 · Viewed 11.4k times · Source

I am new in Angular, I need to implement a function that returns true/false, I going to use the return in canActivate guard, but this function consumes a api by http.get, so like the communication is asynchronous this function always return FALSE, because http.get yet is in process.

My class 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 function isLoggedIn()

isLoggedIn() {

    let logged: boolean = false;

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

    return logged;

}

I read many questions, but I don't found the answer.

Answer

kit picture kit · Sep 29, 2016

guard typings says it 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;
    }
}