作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个名为 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/
我是一名优秀的程序员,十分优秀!