简体   繁体   中英

handle cancelled http request in angular httpclient interceptor

export class AppHttpInterceptor implements HttpInterceptor {

  private cache = new HttpCache();
  private cacheURLList = [];
  count = 0;

  constructor(@Inject(AppBlockUiService) private appBlockUiService: AppBlockUiService,
              @Inject(AppMessageService) private appMessageService: AppMessageService) {

  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const started = Date.now();



    this.blockUi();




    return next.handle(serverReq)
      .timeout(720000)
      .do(
        event => {

          if (event instanceof HttpResponse) {
            this.unBlockUi();

          }
        }, err => {
          if (err instanceof HttpErrorResponse) {
            // this.appBlockUiService.unblockUi();
          }
          this.unBlockUi();

        }
      );

  }




}

So I have an http interceptor that i am using to have a loading mask on ui while making http calls, but i am facing issue that while http request is cancelled because of using unsubscribe or because of timeout. the unblock method is not called.

Is there a way to handle cancelled request via unsubscibed and via timeout?

It might not be elegant but I am using finalize :

  return next.handle(this.addAuthHeader(req)).pipe(
    catchError(err => {
      // console.error('err', err);
      if (err instanceof HttpErrorResponse) {
        this.unBlockUi();
      }
      return throwError(err);
    }),
    tap(res => {
      if (res instanceof HttpResponse) {
        this.unBlockUi();
      }
    }),
    // helps dealing with cancelled requests
    finalize(() => {
       this.unBlockUi();
    })
  );

There is more code in my Interceptor , tried to change it to your unblockUi method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM