简体   繁体   English

将@ngrx 存储作为依赖项注入 Angular 的工厂提供程序中

[英]Inject @ngrx store as dependency in a factory provider in Angular

I'm using a function factory in the app.module of my Angular application to initialise one service.我在 Angular 应用程序的 app.module 中使用函数工厂来初始化一项服务。 Something like this像这样的东西

export function analyticsServiceFactory() {
  return ConfigService.env === "development" ? new AnalyticsDevService() : new AnalyticsService();
}
...
const providers = [
  ...
  { provide: AnalyticsService, useFactory: analyticsServiceFactory }
];

This was working fine until now.到目前为止,这一切正常。 Problem comes because now I need to inject the state (@ngrx) as a dependency to one of those services.问题来了,因为现在我需要将状态(@ngrx)作为这些服务之一的依赖项注入。 How would I do that?我该怎么做?

I know I can add a dependencies to the factory provider, but how do I add the state?我知道我可以向工厂提供程序添加依赖项,但是如何添加状态? Is that even possible?这甚至可能吗?

Also, my store and my analyticsServiceFactory are defined in different modules, which makes it even more difficult.此外,我的 store 和我的 analyticsServiceFactory 定义在不同的模块中,这使得它更加困难。

Any ideas?有任何想法吗? Thanks.谢谢。

您可以在提供者定义的"deps"数组中要求依赖项,然后在工厂函数中将它们作为参数接受:

{ provide: FooService, useFactory: (store: Store<AppState>, httpClient: HttpClient) => { return new FooService(httpClient, store); }, deps: [Store, HttpClient] }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM