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

时间:2019-06-20 15:18:45

标签: angular http angular-http-interceptors

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

2 个答案:

答案 0 :(得分:0)

使用catchError处理程序时,必须使用next RxJs运算符,这是代码:

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运算符。

答案 1 :(得分:0)

您尝试过finalize事件吗?

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