Angular HTTP Interceptors - Redirect to Login page and skip further code execution

霸气de小男生 提交于 2020-02-25 06:10:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!