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

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

问题描述

在任何地方,建议在根 AppModule providers 数组中注册服务,避免使用根 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({ ... providers: []}),则所有组件将共享相同的实例.

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天全站免登陆