如何在Angular 4.3中使用HttpClient的两个实例(一个使用2个拦截器,另一个使用1个拦截器)?
问题描述:
在我们的Angular 4.3
项目中,我们分别具有公共站点组件和安全站点(已登录)组件。我们使用@angular/common/http
。我们希望为public-site
组件和secured-site
组件实施不同的http拦截器。例如,如何在Angular 4.3中使用HttpClient的两个实例(一个使用2个拦截器,另一个使用1个拦截器)?
- 公共现场部件 - 只适用下面拦截
LoggingInterceptor
- 担保现场组件 - 应用下面2个拦截
LoggingInterceptor
AuthTokenInterceptor
(通过在请求报头中的身份验证令牌)
我们尝试添加提供商详细信息HTTP_INTERCEPTORS
在每个组件级别@Component
与不同的拦截器。但是请求没有进入任何拦截器。
仅当我们在@NgModule
中添加提供商详细信息HTTP_INTERCEPTORS
时,请求才会进入拦截器。这里的问题是,公共站点http请求也进入AuthTokenInterceptor
,这是不需要的。
那么我们该如何解决呢?谢谢。
答
您不需要两个HttpClient
实例作为拦截器在每个http请求上重复应用。
我不知道你是如何处理我们的应用程序的状态的,基于你可以在你的拦截器中放置一些条件来决定当前请求是否变异。通过这种方式,如果请求从public-site components
触发,它就不会有附加到它的Authorization
标题。 e.g:
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);
}
}
如果你不想送Authorization
头特别api/url
只使用req.url
上设置一个过滤器。
谢谢@Kuncevic。我们将找到区分公共场所组件请求的条件。但是有一个问题,如果我们在@ Component级别(从@ NgModule中删除)添加HTTP_INTERCEPTORS提供程序,并且如果我们在该组件的ngOnInit方法内进行http调用,则拦截器不会被调用。如果我们将相同的代码行(提供者)移动到@ NgModule,拦截器正在工作。 HTTP_INTERCEPTORS提供程序是否应该仅在NgModule中配置? – Samy
这就是依赖注入的工作原理。即使你把你的'public-site'和'secured-site'放入'modules'中,每一个显然你都必须在'app.module'中声明,然后在'public-site.module'中声明你指定'interceptor1',在'secured-site.module'中指定'interceptor1'和'interceptor2',这样你就可以结束'interceptor1'调用两次。但是,如果您将每个模块都加载得比您可能需要的时间少,因为每个延迟加载模块都有自己的注入树,因此在这种情况下提供程序不会干涉。 – Kuncevic
但我不会推荐使用'lazy loading'模块作为'lazy loading'服务于不同的目的。我不推荐使用'lazy loading'只是为了让'http interceptors' /'provider'申请每个'lazy laded'模块,我希望这很清楚。 – Kuncevic