首页 > 解决方案 > 在 HttpInterceptor 上捕获取消/中止请求。角8

问题描述

我在使用 Angular 8 构建的应用程序中遇到问题。

我有一个应用程序级微调器,它会为每个发出的 http 请求打开并在响应中关闭。

这些请求由显示负载微调器的 HttpInterceptor 捕获,并在获得响应时将其隐藏。当其中一些 http 调用被取消时,问题就出现了,如下例所示:

  search(param: string) {
    return terms.debounceTime(SEARCH_DEBOUNCE)
      .distinctUntilChanged()
      .switchMap(term => this.search(param));
  }

上面的代码属于一个文本搜索引擎,当你停止输入一段时间后,就会执行搜索。当这完成得太快时,可以同时发出多个请求,然后 switchMap 会取消这些请求。出于这个原因,当请求被取消时,拦截器无法获得取消的状态,因此微调器永远不会消失。

拦截器做这样的事情:

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {
    // the spinner is shown

    return next.handle(request).pipe(
      catchError(error => {
        // error handling and spinner stop
      }),
      finalize(() => {
        // Access to all responses except cancelled requests, which have no response.
      })
    );

因此,对于那些请求被取消或中止的情况,我无法停止微调器。

标签: angularhttp

解决方案


如果您的目标是在没有任何特定条件的情况下停止微调器,而只是在 return 语句中,您可以像这样使用点击运算符(https://rxjs-dev.firebaseapp.com/api/operators/tap):

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {
// the spinner is shown

return next.handle(request).pipe(
  catchError(error => {

    // Do things
  }),
  finalize(() => {
   // Do things
  }),
  tap(()=> /* stop spinning */)
);

推荐阅读