如何在 Angular 4.3 中使用两个 HttpClient 实例(一个有 2 个拦截器,另一个有 1 个拦截器)?

Sam*_*amy 5 http-headers angular-http-interceptors angular

在我们的Angular 4.3项目中,我们分别有公共站点组件和安全站点(登录)组件。我们使用@angular/common/http. 我们想为public-site组件和secured-site组件实现不同的http拦截器。例如,

  1. 公共站点组件 - 仅在拦截器下方应用
    LoggingInterceptor
  2. 安全站点组件 - 在两个拦截器下方应用
    LoggingInterceptor
    AuthTokenInterceptor(在请求标头中传递身份验证令牌)

我们尝试使用不同的拦截器HTTP_INTERCEPTORS在每个组件级别添加提供者详细信息@Component。但是请求不会进入任何拦截器。

仅当我们HTTP_INTERCEPTORS@NgModule. 这里的问题是,公共站点 http 请求也会进入AuthTokenInterceptor不需要的。

那么我们应该如何解决这个问题呢?谢谢。

Kun*_*vič 0

您不需要HttpClient在每个 http 请求上反复应用两个 as 拦截器实例。

我不知道您如何处理我们应用程序的状态,基于此您只需在拦截器中添加一些条件,该条件将决定当前请求是否发生变化。这样,如果请求触发,public-site components则不会Authorization附加标头。例如:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if ('your condition here if public-site components') {
        // Just return original request
        return next.handle(req);
    } else {
        // Here return modified one
        // Get the auth header from the service.
        const authHeader = this.auth.getAuthorizationHeader();
        // Clone the request to add the new header.
        const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
        // Pass on the cloned request instead of the original request.
        return next.handle(authReq);
     }

   }
Run Code Online (Sandbox Code Playgroud)

如果您不想将Authorization标头发送到特定的位置,api/url只需req.url在其上设置过滤器即可。