Angular 2 – 作为NgModule服务而不必声明所有提供者?
发布时间:2020-12-17 10:24:04 所属栏目:安全 来源:网络整理
导读:我有一个名为CalculationService的服务,它被声明为@Injectable().此服务使用大量其他注入类,每个类也声明为@Injectable(),并通过@Inject()提供给CalculationService的构造函数. 现在,当我想在我的应用程序中使用该服务时,AppComponent看起来像这样(为了方便
我有一个名为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,但我不知道如何在服务中声明提供者. 有没有办法将服务重构为模块,即在CalculationService中声明提供程序?或者我必须摆脱所有@Injectable()s(Bausparen等)并在计算服务中创建对象,以便不需要提供者?
您无法在服务上或服务中注册提供商.您只能在模块或组件中注册它们.
您可以做的是为您的服务创建一个模块,然后您只需要将模块添加到导入:[…]并且所有提供者都在全球注册. 如果它是一个延迟加载的模块,你需要实现并导入forRoot() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |