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

pes8fvy9  于 2023-09-28  发布在  Ionic
关注(0)|答案(3)|浏览(173)

大多数httpClient拦截器教程都捕获错误响应以显示警报。
示例如下:
https://ionicacademy.com/ionic-http-interceptor/
https://medium.com/@deniscangemi/intercept-http-requests-in-angular-c6392b7b0e0
是否可以使用拦截器为每个HTTP请求提供一个加载器?
如果是,如何处理或捕获成功的HTTP请求,以解除加载器。

62lalag4

62lalag41#

你也可以在管道中添加一个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
                })
            );
8e2ybdfx

8e2ybdfx2#

我写了一个简单的服务,它允许我在整个应用程序中启用/禁用加载器。您只需为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)">

nhaq1z21

nhaq1z213#

您可以使用map并验证响应中是否有任何错误。

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

解决方案二:正在使用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);
                       })
                    );
                  }
                }

相关问题