在角度httpclient拦截器中处理已取消的http请求

时间:2019-04-19 02:21:11

标签: angular typescript rxjs httpclient angular-http-interceptors

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请求被取消了。取消调用方法不会被调用。

是否可以通过取消订阅和超时来处理已取消的请求?

1 个答案:

答案 0 :(得分:1)

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

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