【问题标题】:How to intercept a cancelled http request in Angular?如何在 Angular 中拦截取消的 http 请求?
【发布时间】:2019-06-20 15:18:45
【问题描述】:

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

【问题讨论】:

标签: angular http angular-http-interceptors


【解决方案1】:

你尝试过 finalize 事件吗?

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

【讨论】:

  • 我如何确定哪个请求在 finalize 中被取消了?它是否有任何特定的键表明特定的请求已被取消?
【解决方案2】:

在使用next Handler 时,必须使用catchError 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 操作符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 2018-03-08
    • 2017-07-13
    • 1970-01-01
    相关资源
    最近更新 更多