ssantamariaparra
ssantamariaparra

Reputation: 13

Angular 6 - Return value on http error

i'm trying to protect my routes by implementing an asynchronous guard. To do so, I've created an AuthService with a method called isUserLoggedIn that consumes information from an API.

auth.service.ts

isUserLoggedIn(): Observable<boolean> {
    return this.http.get<HttpApiResponse>(AppSettings.API_ENDPOING + 'auth/test').pipe(
      map(response => response.data.logged)
    );
  }

And I have a guard that uses the service, if the user is logged in, the access is denied, but if the user is not logged in the access is granted.

export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService) { }

    canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.auth.isUserLoggedIn().pipe(
      retry(3),
      map(response => !response)
    );
  }
}

By here, everything is working properly. Now what I need is to grant the access to the user when the API is not responding or responds with error codes.

Upvotes: 0

Views: 1943

Answers (2)

ssantamariaparra
ssantamariaparra

Reputation: 13

As SplitterAlex told me, I used the catchError inside pipe to handle the error as follows.

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.auth.isUserLoggedIn().pipe(
      retry(3),
      map(response => !response),
      catchError(error => {
        return of(true);
      })
    );
  }

An important thing here was to import of from 'rxjs' to be able to return true or false inside the catchError.

Upvotes: 1

SplitterAlex
SplitterAlex

Reputation: 2823

You can catch a http error with the catchError operator and handle the error accordingly.

export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService) { }

    canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | 
Promise<boolean> | boolean {
    return this.auth.isUserLoggedIn().pipe(
      retry(3),
      map(response => !response),
      catchError(err => {
        // handle error, check error code and return true or 
             false
      })
    );
  }
}

Upvotes: 1

Related Questions