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

问题描述 投票:1回答:1
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拦截器,我正在使用ui加载掩码进行http调用,但我面临的问题是,由于使用取消订阅或因超时而取消了http请求。 unblock方法不会被调用。

有没有办法通过unsubscibed和via timeout处理已取消的请求?

angular typescript rxjs httpclient angular-http-interceptors
1个回答
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方法。

© www.soinside.com 2019 - 2024. All rights reserved.