Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - return boolean with subscribe to canActivate

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.

like image 914
Rit Avatar asked Sep 29 '16 13:09

Rit


1 Answers

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;
    }
}
like image 81
kit Avatar answered Nov 16 '22 12:11

kit