【问题标题】:Preventing hierachical dependency injection in Angular 6防止 Angular 6 中的分层依赖注入
【发布时间】: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


【解决方案1】:

我通过在我的用户服务的构造函数中创建一个新的注入器实例来解决这个问题。这样,将不会使用来自外部应用程序的 HttpClient,而是使用角度实现:

constructor(
    private httpHandler: HttpHandler
) {
    const injector = Injector.create(
        {
            providers: [
                { provide: HttpClient, useClass: HttpClient, deps: [HttpHandler] },
                { provide: HttpHandler, useValue: httpHandler }
            ]
        }
    );

    this.httpClient = injector.get(HttpClient);
}

【讨论】:

    猜你喜欢
    • 2013-04-30
    • 2019-03-04
    • 2019-04-02
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多