0

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.

2 Answers 2

1

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
      })
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Do you mind accept my answer as vaild answer? I think it helped you :) Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.