【问题标题】:Angular 2 - Service as NgModule to not have to declare all providers?Angular 2 - 作为 NgModule 的服务不必声明所有提供者?
【发布时间】:2016-09-06 08:36:57
【问题描述】:

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

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

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

【问题讨论】:

    标签: angular angular2-services


    【解决方案1】:

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

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

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

    【讨论】:

    • 当我将我的服务声明为 NgModule 时,那么在 declarationsbootstrap 中添加什么?
    • 其实我自己没有试过没有declarations的模块,但我会尽量省略declarationsbootstrap
    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 2017-08-22
    • 2016-09-10
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多