I am building an angular app that uses jwt token for authentication.I'm saving the token in local storage to authenticate the rest calls from frontend. My issue is that when the jwt token expires from the server,the application displays no data as the jwt token has expired but the local storage still has expired token. I looked into this Handling Expired Token From Api in Angular 4 but I'm unable to understand what to do.Please help.Thanks in advance.
Here is my auth guard:
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (localStorage.getItem('user')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return true;
}
}
My error interceptor:
@Injectable()
export class H401Interceptor implements HttpInterceptor {
constructor(private authService: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 401) {
// auto logout if 401 response returned from api
// this.authService.logout();
// location.reload(true);
localStorage.removeItem('currentUser');
}
const error = err.error.message || err.statusText;
return throwError(error);
}));
}
}