Reputation: 13
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
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
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