在角度httpclient拦截器中处理已取消的http请求 [英] handle cancelled http request in angular httpclient interceptor

查看:124
本文介绍了在角度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请求被取消了.取消调用方法不会被调用.

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?

推荐答案

它可能并不优雅,但我正在使用finalize:

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

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

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

这篇关于在角度httpclient拦截器中处理已取消的http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆