【问题标题】:handle cancelled http request in angular httpclient interceptor在 Angular httpclient 拦截器中处理取消的 http 请求
【发布时间】:2019-04-19 02:21:11
【问题描述】:
export class AppHttpInterceptor implements HttpInterceptor {

  private cache = new HttpCache();
  private cacheURLList = [];
  count = 0;

  constructor(@Inject(AppBlockUiService) private appBlockUiService: AppBlockUiService,
              @Inject(AppMessageService) private appMessageService: AppMessageService) {

  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const started = Date.now();



    this.blockUi();




    return next.handle(serverReq)
      .timeout(720000)
      .do(
        event => {

          if (event instanceof HttpResponse) {
            this.unBlockUi();

          }
        }, err => {
          if (err instanceof HttpErrorResponse) {
            // this.appBlockUiService.unblockUi();
          }
          this.unBlockUi();

        }
      );

  }




}

所以我有一个 http 拦截器,用于在进行 http 调用时在 ui 上设置一个加载掩码,但我面临的问题是,由于使用取消订阅或超时而取消了 http 请求。不调用 unblock 方法。

有没有办法通过取消订阅和超时来处理取消的请求?

【问题讨论】:

    标签: angular typescript rxjs httpclient angular-http-interceptors


    【解决方案1】:

    它可能不优雅,但我使用的是finalize

      return next.handle(this.addAuthHeader(req)).pipe(
        catchError(err => {
          // console.error('err', err);
          if (err instanceof HttpErrorResponse) {
            this.unBlockUi();
          }
          return throwError(err);
        }),
        tap(res => {
          if (res instanceof HttpResponse) {
            this.unBlockUi();
          }
        }),
        // helps dealing with cancelled requests
        finalize(() => {
           this.unBlockUi();
        })
      );
    

    我的Interceptor中有更多代码,尝试将其更改为您的unblockUi方法。

    【讨论】:

    • do方法呢?
    • 还有什么进口?我正在使用 rx 5.5
    • 啊,我已经忘记了 5.5 :) 6 中的 IIRC tap 是 5.x 中的 do。尝试搜索 finalize 的等价物……抱歉。
    • 我如何确定在finalize 中被取消的请求?它是否有任何特定的键表明特定的请求已被取消?
    猜你喜欢
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 2020-09-07
    相关资源
    最近更新 更多