向NgModule提供服务与组件之间的区别 [英] Difference between providing a service to NgModule vs Component

查看:147
本文介绍了向NgModule提供服务与组件之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们刚刚开始使用angular2进行第一个项目.我对提供服务有疑问.

We are just on our first project with angular2. I've got a question about providing a service.

据我所知,有两种方法可以使用您的应用程序中的 providers:[MyService] 声明提供程序.您可以在 @NgModule 标记中全局声明,也可以在 @Component 标记中局部声明.

As I know, there are two ways to declare a provider with providers:[MyService] in your app. You can declare it globally in the @NgModule tag or locally in the @Component tag.

据我所知,两种方式之间的唯一区别是提供范围.一旦应用广泛,一次就只有组件广泛.由此得出的结论是,我应该更喜欢在我的特定组件中主要提供一个本地服务(取决于服务的使用情况),以保持范围较小.

As far as I know, the only difference between the two ways is the providing scope. Once app wide, once only component wide. Out of this I would make the conclusion, that I should prefer to provide a service mostly (depending on the usage of the service) local in my specific component to keep the scope small.

是正确的,还是我不知道的两种声明方式之间有其他区别?

Is that correct, or are there any other differences between the two declaration ways, which I'm not aware of?

推荐答案

如果您提供组件本地的服务,则它们将不会具有SAME服务.他们获得相同类型的所有A服务,但它们不是相同的.

If you provide a service local to your components they will NOT have the SAME service. They get all A service of the same type, but they will be not the SAME one.

如果将它们提供给AppModule,则会将其创建为整个应用的单例.

If you provide them to your AppModule, the will be created as a singleton for the whole app.

这篇关于向NgModule提供服务与组件之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆