如何拦截Angular中取消的http请求?

How to intercept a cancelled http request in Angular?

Angular 取消 http 请求非常快,我想拦截那些取消的请求。 是否可以在拦截器中捕获取消的请求? 下面是我的拦截器代码片段,我想在其中捕获已取消的请求。

  intercept(req: HttpRequest<any>, next: HttpHandler): 
Observable<HttpEvent<any>> {
    this.onStartRequest();
    // Pass the cloned request instead of the original request to the next handle
    return next.handle(req).do(
      (event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
         // do something
        }
      },
      (err: any) => {
        if (err instanceof HttpErrorResponse) {
          // do something
        }
      }
    );
  }

使用nextHandler时必须使用catchErrorRxJs运算符,代码如下:

intercept(req: HttpRequest<any>, next: HttpHandler): 
Observable<HttpEvent<any>> {
    this.onStartRequest();
    // Pass the cloned request instead of the original request to the next handle
    return next.handle(req).do(
      (event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
         // do something
        }
      })
      .catchError((err: HttpErrorResponse) => {
        // Handle errors
      });
  }

PS: 不要忘记导入 catchError 运算符。

你试过 finalize 事件吗?

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