如何在Angular中有条件地添加HttpClient拦截器

Rah*_*ngh 10 angular-http angular-http-interceptors angular angular-httpclient

最近我一直在使用Angular HttpClient拦截器.

我添加了与某些HTTP GET方法相对应的标头,对于某些我不需要这些标头.

如何告诉我的拦截器有条件地将拦截器添加到那些方法?我甚至可以拆分服务,例如一个服务用于标头,一个服务没有标题,一个用于不同的标题,一个用于不同的标题.

NgModule提供商

{
  provide: HTTP_INTERCEPTORS,
  useClass: AuthInterceptor,
  multi: true,
},{
  provide: HTTP_INTERCEPTORS,
  useClass: AngularInterceptor,
  multi: true,
}
Run Code Online (Sandbox Code Playgroud)

MyInterceptors

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authReq = req.clone({headers: req.headers.set('X-Auth-Token', "-------------------------")});
    return next.handle(authReq);

  }
}


@Injectable()
export class AngularInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(event => {}, err => {
        if(err instanceof HttpErrorResponse){
            console.log("Error Caught By Interceptor");
            //Observable.throw(err);
        }
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*lph 1

注意:我自己还没有尝试过这种方法,但已经尝试过这个想法,因为我们正在研究类似的问题。

\n\n

如果我们的需求非常简单,那么在通用拦截器中添加逻辑并根据 URL/方法决定要执行哪种拦截就很简单了。然而,我们的 Angular 应用程序需要调用各种第一方微服务和第三方 API,对拦截器有不同的要求。这实际上是您的要求的超集。

\n\n

实现此目的的一个想法是为我们需要调用的每个 API/服务扩展 HttpClient,并为拦截器链设置自定义注入令牌。HttpClient 您可以在此处查看 Angular 如何注册默认值:

\n\n
 providers: [\n    HttpClient,\n    // HttpHandler is the backend + interceptors and is constructed\n    // using the interceptingHandler factory function.\n    {\n      provide: HttpHandler,\n      useFactory: interceptingHandler,\n      deps: [HttpBackend, [new Optional(), new Inject(HTTP_INTERCEPTORS)]],\n    },\n
Run Code Online (Sandbox Code Playgroud)\n\n

interceptingHandler函数甚至导出\xc9\xb5interceptingHandler. 我同意这看起来有点奇怪,不知道为什么它有那个导出名称。

\n\n

无论如何,要使用自定义 HttpClients,您可能可以:

\n\n
export const MY_HTTP_INTERCEPTORS = new InjectionToken<HttpInterceptor[]>(\'MY_HTTP_INTERCEPTORS\');\n\n...\n providers: [\n    MyHttpClient,\n    {\n      provide: MyHttpHandler,\n      useFactory: interceptingHandler,\n      deps: [HttpBackend, [new Optional(), new Inject(MY_HTTP_INTERCEPTORS)]],\n    },\n
Run Code Online (Sandbox Code Playgroud)\n\n

并确保其构造函数中MyHttpClient需要 a MyHttpHandler

\n