如何使用httpClient拦截器捕获成功的请求?

问题描述 投票:0回答:4

大多数 httpClient 拦截器教程都是捕获错误响应以显示警报。

示例:

https://ionicacademy.com/ionic-http-interceptor/

https://medium.com/@deniscangemi/intercept-http-requests-in-angular-c6392b7b0e0

是否可以使用拦截器为每个 HTTP 请求提供一个加载器?

如果是,如何处理或捕获成功的 HTTP 请求以关闭加载程序。

angular http ionic-framework interceptor angular-http-interceptors
4个回答
3
投票

您也可以在管道内添加一个

tap
函数,该函数将在每次运行时执行,如下所示:

            import { tap, catchError } from 'rxjs/operators';

            // ...

            return next.handle(clonedReq).pipe(
                tap(data => {
                  // Do your success stuff in here
                }),
                catchError(error => {
                  // Do your error handling in here
                })
            );

0
投票

我编写了一个简单的服务,它允许我在整个应用程序中启用/禁用加载程序。您只需为 API 调用提供唯一的名称:

import { Injectable } from "@angular/core";

@Injectable({
    providedIn: "root"
})
export class WatcherService {
    private watchers = new Map<String, Boolean>();

    public isLoading(watcher: String): Boolean {
        return this.watchers.get(watcher) || false;
    }

    public start(watcher: String) {
        this.watchers.set(watcher, true);
    }

    public stop(watcher: String) {
        this.watchers.set(watcher, false);
    }
}

例如,密钥可以是 API 端点 URL。您可以将观察者注入拦截器中。

通过这种方式,您可以在任何地方显示加载程序,而不必担心在多层组件之间传递标志/事件,只是为了显示加载程序。

例如,我的应用程序中有一个列表。我可以从许多地方(过滤器、搜索栏或用户向下滚动后)获取列表的新项目。我不必将所有组件连接到我的列表来显示加载程序,我只需调用:

watcher.start('actionName')

并且列表知道,它应该显示加载程序:

<qlisting [loading]="watcher.isLoading(getUnitsActionName)">


0
投票

您可以使用地图来验证您的回复是否有错误。

import { map } from 'rxjs/operators';
import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
  HttpResponse
} from '@angular/common/http';
    
    
    export class HttpInterceptorInterceptor implements HttpInterceptor {
            
              constructor() { }
            
              intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
            
                return next.handle(request).pipe(
                  map((event: HttpEvent<any>) => {
                    if (event instanceof HttpResponse) {
                      if (event.ok) {
                         console.log('Success');
                      } else {
                        console.log('Error');
                      }
                    }
            
                    return event;
                  })
                );
              }
            }

解决方案2: 使用 catchError .

import { map, catchError } from 'rxjs/operators';
    import {
      HttpEvent,
      HttpHandler,
      HttpInterceptor,
      HttpRequest,
      HttpResponse
    } from '@angular/common/http';
        
        
        export class HttpInterceptorInterceptor implements HttpInterceptor {
                
                  constructor() { }
                
                  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
                
                    return next.handle(request).pipe(
                      map((event: HttpEvent<any>) => {
                        if (event instanceof HttpResponse) {
                          if (event.ok) {
                             console.log('Success');
                          } else {
                            console.log('Error');
                          }
                        }
                
                        return event;
                      }),catchError((error: HttpErrorResponse) => {
                            let errorMsg = '';
                            if (error.error instanceof ErrorEvent) {
                                errorMsg = `Error: ${error.error.message}`;
                                console.log('This is client side error');
                            } else {
                                errorMsg = `Error Code: ${error.status},  Message: ${error.message}`;
                                console.log('This is server side error');
                            }
                            console.log(errorMsg);
                            return throwError(() => errorMsg);
                       })
                    );
                  }
                }

0
投票
return next.handle(req).pipe(
  tap({
    next: (event) => {
      if (event instanceof HttpResponse) {
        document.write('tap ');
      }
    },
  }),
  finalize(() => {
    document.write('finalize ');
  })
);

https://stackblitz.com/edit/tap-tap-finalize-aqjtms?file=src%2Fapp%2Finterceptor.ts

© www.soinside.com 2019 - 2024. All rights reserved.