首页 > 解决方案 > 在 Angular httpclient 拦截器中处理取消的 http 请求

问题描述

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();

        }
      );

  }




}

所以我有一个 http 拦截器,我在进行 http 调用时使用它在 ui 上设置一个加载掩码,但我面临的问题是,由于使用取消订阅或超时,http 请求被取消。不调用 unblock 方法。

有没有办法通过取消订阅和超时来处理取消的请求?

标签: angulartypescriptrxjshttpclientangular-http-interceptors

解决方案


它可能不优雅,但我正在使用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();
    })
  );

my 中有更多代码Interceptor,尝试将其更改为您的unblockUi方法。


推荐阅读