在根AppModule或根AppComponent中注册服务 [英] Register service in root AppModule or root AppComponent

查看:175
本文介绍了在根AppModule或根AppComponent中注册服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在任何地方,建议在根AppModule提供程序数组中注册服务,并避免使用根AppComponent的providers数组。
何时应该在根AppComponent中注册服务?任何实际的例子。
与根AppComponent相比,在根AppModule中注册服务有什么优势?

Everywhere, it is recommended to register a service in root AppModule providers array and avoid using providers array of root AppComponent. When should someone register a service in root AppComponent? Any practical example. What is the advantage of registering service in root AppModule compared to root AppComponent?

推荐答案

在根处注册时,与组件中的提供相反,所提供的服务是作为一个单独的实例创建的,它将与您使用该组件时创建的实例数量一样多。

When registered at the root, the provided service is created as a singleton, as opposite to providing in the component, it will be created as many instances as you use the component.

换句话说:

在整个应用程序中都可以访问在根级别注入的服务。 >
组件级别提供的服务仅在该组件及其子组件上可用。

In other words:
The service injected at the root level will be accessible in the entire application.
The service provided at the component level will be available only on that component and its children.

如果您将服务注入多个组件( @Component({... providers:[] ..} ),每个人都将拥有自己的实例,他们的孩子将共享同一实例。

如果您在根级别( @NgModule({... provider:[]} )注入,所有组件将共享同一实例。

In case you inject the service in multiple components (@Component({ ...providers: [] ..}), each will get it's own instance and their children will share that same instance.
If you inject in root level (@NgModule({ ... providers: []}), all components will share the same instance.

了解更多信息此处

这篇关于在根AppModule或根AppComponent中注册服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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