Simplest way to return boolean from Observable

241 views Asked by At

I want to get boolean for canActivate() method but nothing is working. My code is:

  login() {
      return this.http.get<any>('http://localhost/auth');
  }

and I want to do somthing like this:

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.authenticationService.login().subscribe(
      () => true,
    () => false
    );
  }

What is the correct way to do this?

1

There are 1 answers

0
Adrien SAULNIER On BEST ANSWER

You don't need to subscribe in a canActivate method from a route Guard : In fact, Guard can return Observable and Angular will subscribe to it.

Just use rxjs map operator, such as :

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  return this.authenticationService.login().pipe(
    map(response => /* do your stuff and return true to allow route access */)
    catchError(error => of(false)) // Auth failed : return false to prevent route access
  )
}

See more here