Angular 5/HttpInterceptor/检测(取消)xhr [英] Angular 5 / HttpInterceptor / Detect (cancelled) xhr

查看:82
本文介绍了Angular 5/HttpInterceptor/检测(取消)xhr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的角度应用程序中,我看到Chrome(取消)API调用触发得太快.我还拥有一个HttpInterceptor,如果请求未完成,则它会在500ms之后触发每个HttpClient请求的加载指示器.但是,在收到(取消)的请求上,似乎没有任何新事件可随后隐藏我的加载指示器.

In my angular app I'm seeing chrome (cancel) api calls that fire off too rapidly. I also have an HttpInterceptor that triggers a loading indicator with every HttpClient request after 500ms if the request has not completed. However, on the requests that get (cancelled) there does not seem to be any new event to subsequently hide my loading indicator.

是否可以在HttpInterceptor中检测已取消"的请求,以便再次隐藏加载指示器?

Is there a way to detect 'cancelled' requests in the HttpInterceptor so I can hide my loading indicator again?

  export class GlobalHttpInterceptor implements HttpInterceptor {
    constructor(
      private sessionService: SessionService,
      private loadingService: LoadingService
    ) { }

    intercept(
      req: HttpRequest<any>,
      next: HttpHandler
    ): Observable<HttpEvent<any>> {

      setTimeout(() => {
        if (showLoading) {
          this.loadingService.show();
        }
      }, 500);
      let showLoading = true;

      if (this.sessionService.headers.length > 0) {
        for (const x of this.sessionService.headers) {
          req = req.clone({
            headers: req.headers.set(x.key, x.value)
          });
        }
      }

      return next.handle(req)
        .do(
          (response) => {
            if (response instanceof HttpResponse) {
              showLoading = false;
              this.loadingService.hide();
            }
          },
          (error) => {
            showLoading = false;
            this.loadingService.hide();
          }
        );
    }
  }

推荐答案

遇到了同样的问题.即使取消了http请求, finalize 运算符似乎也会触发.

Just encountered the same problem. The finalize operator seems to trigger even when the http request is cancelled.

    public intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
        // request starts

        return next.handle(request).pipe(
            finalize(() => {
                // request completes, errors, or is cancelled
            })
        );
    }

这篇关于Angular 5/HttpInterceptor/检测(取消)xhr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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