gpt4 book ai didi

Angular 2 - 作为 NgModule 的服务不必声明所有提供者?

转载 作者:太空狗 更新时间:2023-10-29 17:37:16 25 4
gpt4 key购买 nike

我有一个名为 CalculationService 的服务,声明为 @Injectable()。该服务使用了大量其他注入(inject)类,每个类也声明为 @Injectable() 并通过 @Inject() 提供给 CalculationService 的构造函数。

现在,当我想在我的应用程序中使用该服务时,AppComponent 看起来像这样(为了方便起见,我省略了 Typescript 导入):

@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
RouterModule.forRoot(routeConfig),
PlannerModule
],
providers: [
InputService,
Bausparen,
BausparenInput,
Girokonto,
GirokontoInput,
Immobilien,
ImmobilienInput,
Lebensversicherung,
LebensversicherungInput,
Rentenversicherung,
RentenversicherungInput,
Tagesgeld,
TagesgeldInput,
Termingeld,
TermingeldInput,
Wertpapiere,
WertpapiereInput
],
bootstrap: [AppComponent]
})
export class AppModule {
}

我不需要直接访问应用模块中声明的所有提供程序。唯一需要的类是 CalculationService,但我不知道如何在服务中声明提供者。

有没有办法将服务重构为模块,即在 CalculationService 中声明提供者?或者我是否必须摆脱所有的 @Injectable()(Bausparen 等)并在计算服务中创建对象,这样就不需要提供程序了?

最佳答案

您不能在服务上或服务中注册提供商。您只能在模块或组件中注册它们。

你可以做的是为你的服务创建一个模块,然后你只需要将模块添加到 imports: [...] 并且所有提供者都在全局注册。

如果是懒加载模块你需要实现并导入forRoot()

关于Angular 2 - 作为 NgModule 的服务不必声明所有提供者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39344334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com