【发布时间】:2018-10-14 23:41:31
【问题描述】:
tl;dr: 如何防止 Angular 在较低级别的模块中注入 HttpClient 的自定义实现?相反,我想使用 Angular 附带的标准实现(例如,没有拦截器)。
我使用 Angular CLI 构建了一个 Angular 6 库。这个库还导出了一个模块和一个服务,为我提供身份管理功能(自写)并使用 HttpClientModule 向 api 服务器发送请求。
在我的应用程序中,我引用了这个库(通过私有 npm 打包),它运行良好。
最近,我偶然发现 HttpInterceptors 可以将功能扩展到 ngx 火箭入门套件中已经存在的 HttpClient。您可以在此处找到 HttpClient 实现的代码:https://github.com/ngx-rocket/starter-kit/blob/master/src/app/core/http/http.service.ts
当我在我的应用模块的 providers 数组中提供我自己的 HttpClient 实现时,似乎由于 Angular 分层依赖注入,我的库也将使用提供的自定义实现,尽管我不希望它这样做.
所以我的问题是: 如何防止 Angular 在较低级别的模块中注入 HttpClient 的自定义实现?相反,我想在较低级别的模块中使用标准实现(例如,没有拦截器)。
我已经尝试过的是提供
{ provide: HttpClient, useValue: HttpClient }
在我的用户服务(请在下面找到代码)中不起作用。
此代码在我的应用程序中:
app.module.ts
/* other module code */
imports: [
UserModule
],
providers: [
{ provide: HttpClient, useValue: MyOwnHttpClientImplementation }
]
/* other module code */
此代码在库中:
user.module.ts
/* other module code */
imports: [
HttpClientModule
/* At this point, I want to use the standard HttpClient implementation */
],
providers: [
UserService,
{ provide: HttpClient, useValue: HttpClient }
]
/* other module code */
user.service.ts
/* Here are standard HttpClient .get requests, which unfortunately
use the interceptors that are being provided by the application that
uses the library and the user module / service */
【问题讨论】:
-
不应该是
useClass而不是useValue吗?{ provide: HttpClient, useClass: HttpClient } -
你是对的,尽管这不是解决方案
标签: angular typescript dependency-injection