简体   繁体   English

哪里最好注册Angular 2提供者

[英]Where best to register Angular 2 providers

I wrote three services for an Angular 2 app, with the configuration that two are injected into the third and used there. 我为Angular 2应用程序编写了三项服务,其配置是将两项注入第三项并在其中使用。 After importing the two (all three decorated with @Injectable() ), I still received an unknown provider error. 导入两个(全部三个都用@Injectable()装饰)之后,我仍然收到未知的提供程序错误。

To solve it I attempted to place the injected services into the modules providers array, which worked. 为了解决这个问题,我尝试将注入的服务放入有效的模块提供程序数组中。 Is this the best approach? 这是最好的方法吗?

Angular documentation shows listing injectables at the component level. Angular文档显示了在组件级别列出的注射剂。 Can I just place all injectables into the modules providers array? 我可以只将所有注射剂放入模块提供者阵列中吗?

Seems like this would simplify application setup as everything is configured in a central location for each module. 似乎这样可以简化应用程序的设置,因为所有内容都在每个模块的中央位置进行配置。 No searching for dependencies on a component by component basis. 无需在每个组件的基础上搜索依赖项。

Yes, put it in the @NgModule.providers if the service is to be application scoped (singleton). 是的,如果服务要在应用程序范围内(单个),则将其放在@NgModule.providers Only add it to the @Component.providers if the service should be component scoped 1 (each component should get its own instance) 仅当服务的作用域范围为1时,才将其添加到@Component.providers (每个组件应具有自己的实例)


1 - See also Hierarchical Injectors 1-另请参见分层注入器

It depends upon your requirement that what kind of service you want. 这取决于您的要求,即您想要哪种服务。

Singleton service 单身人士服务

If you want to use singleton service , you can place your service somewhere in central area. 如果要使用singleton service ,可以将服务放置在中心区域中的某个位置。 You will think you should use/place service in AppModule . 您会认为应该在AppModule使用/放置服务。 But still to achieve true singleton pattern/instance you should place/declare service in CoreModule-please check how to user CoreModule and then import CoreModule to AppModule . 但是仍然要实现真正的单例模式/实例,您应该在CoreModule中放置/声明服务-请检查如何使用CoreModule ,然后将CoreModule导入AppModule

Multiple Instance service 多实例服务

If you declare serivce in @Component decorator of the components, you will have different instances of the service in different components. 如果在组件的@Component decorator中声明服务,则在不同的组件中将具有服务的不同实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM