问题
I have developed the Angular 6 application. Implemented the JWT token authentication using Web API. Also implemented the HttpInterceptor to keep watch on request and send the token in every request.
@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {
constructor(private router: Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
var token = localStorage.getItem("bearerToken");
if (token) {
const newReq = req.clone(
{
headers: req.headers.set('Authorization', 'Bearer ' + token)
});
return next.handle(newReq)
.do(
(event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
return event;
}
else if (event instanceof HttpErrorResponse){
console.log("event");
}
},
(err) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
return this.router.navigate(['/logout']);
}
}
}
);
}
else {
return next.handle(req);
}
}
};
this.http.post<any[]>(url, JSON.stringify(this.selectedStatus), httpOptions)
.subscribe(response => {
this.view = response;
//this.fetchConfig();
this.showLoader = false;
this.showGrid = true;
},
(err: any) => {
this.showLoader = false;
this.showGrid = true;
if (this.modalRef == null) {
this.modalRef = this.modalService.open(ModalMessageboxComponent);
this.modalRef.componentInstance.message = "An error has occured while accessing the request";
this.modalRef.componentInstance.messageBoxTitle = "Error";
this.modalRef.result.then((result) => {
this.modalRef = null;
}
)
}
}
)
This correctly navigate the application to logout page when we get 401 response from API after token expires. But the catch block written in HTTP request is still executing after redirection to logout page in which i have written page error popup. How to avoid this page error popup when redirection happen to logout ?
来源:https://stackoverflow.com/questions/51961409/angular-http-interceptors-redirect-to-login-page-and-skip-further-code-executi