Angular 5 / HttpInterceptor / Detect(已取消)xhr

前端之家收集整理的这篇文章主要介绍了Angular 5 / HttpInterceptor / Detect(已取消)xhr前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的角度应用程序中,我看到chrome(取消)api调用太快了.我还有一个HttpInterceptor,如果请求没有完成,它会在500ms后触发每个HttpClient请求的加载指示符.但是,对于获取(取消)的请求,似乎没有任何新事件随后隐藏我的加载指示器.

有没有办法在HttpInterceptor中检测“已取消”的请求,以便我可以再次隐藏我的加载指示器?

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运算符似乎也会触发.

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

猜你在找的Angularjs相关文章