0
votes

In angular I have an authguard class that implements canActivate. It must return boolean | Observable | promise etc. I need to call a http.get request to my server that will return either "true" or "false" depending on if user meets a certain condition, to protect certain routes.

How can I make the http request from the guard, wait for it to return (or timeout?) and use the response to return true or false. Also how can i handle errors and return false by default? I know how to use next and error in observable subscribe. Other answers have referred to pipe and map but are outdated or don't work.

1

1 Answers

0
votes

You could return an Obsrvable<boolean> without havnig to subscribe to it.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
  return this.http.get<boolean>('/auth/authenticated')
    .pipe(
      timeout(10000), // wait for 10 seconds before fail.
      map(x => x), // return the received value true/false
      catchError(() => of(false))
    );
}