Angular:如何知道请求是否已在 HttpClient 中取消

kar*_*una 6 angular2-http angular

要知道请求是否已完成,我会这样做if (httpEvent instanceof HttpResponse)。同样,如何知道请求是否在 中被取消HttpInterceptor?下面是我的intercept功能。

intercept(httpRequest: HttpRequest<any>, httpHandler: HttpHandler): Observable<HttpEvent<any>> {
    this.requestsPending++;

    if (this.typeAheads.includes(httpRequest.url.split('/').pop()))
      this.slimLoadingBarService.start();
    else
      this.flsLoaderService.start();

    return httpHandler.handle(httpRequest)
      .do((httpEvent: HttpEvent<any>) => {
        if (httpEvent instanceof HttpResponse) {
          // decrementing counter on each request return
          this.requestsPending--;

          if (this.typeAheads.includes(httpEvent.url.split('/').pop())) {
            if (this.requestsPending === 0)
              this.slimLoadingBarService.complete();
          }
          else {
            if (this.requestsPending === 0)
              this.flsLoaderService.stop();
          }
        }
      }, () => {
        this.slimLoadingBarService.complete();

        // reset counter on error
        this.requestsPending = 0;
        this.flsLoaderService.stop();
      });
  }
Run Code Online (Sandbox Code Playgroud)

Roo*_*omy 5

我也遇到了这个问题,这是我最近想到的解决方案:

要知道请求是否被取消,您可以使用finally运算符,示例如下:

let cancelled = true;
return next.handle(request).do(
  undefined,
  () => {
    // error
    cancelled = false;
  },
  () => {
    // completed
    cancelled = false;
  },
).finally(
  () => {
    if (cancelled) {
      // do things
    }
  },
);
Run Code Online (Sandbox Code Playgroud)


Moh*_*ara 0

看起来 Angular 忽略了中止事件。这是角度来源:https://github.com/angular/angular/blob/5.0.1/packages/common/http/src/xhr.ts

如果请求被中止,返回的 Observable 不会通知订阅者。