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

Angular 2 - Service as NgModule to not have to declare all providers?

我有一个名为 CalculationService 的服务,声明为 @Injectable()。该服务使用了大量其他注入的 classes,每个也被声明为 @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 {
}

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

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

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

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

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