Angular 6 服务:providIn: 'root' vs CoreModule [英] Angular 6 Services: providedIn: 'root' vs CoreModule
问题描述
使用 Angular 6,以下是创建单例服务的首选方式:
With Angular 6, below is the preferred way to create singleton services:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class UserService {
}
来自 Angular 文档:当你在根级别提供服务时,Angular 会创建一个单一的 HeroService 共享实例,并注入到任何需要它的类中.在@Injectable 元数据中注册提供者还允许 Angular 通过删除服务来优化应用程序,如果它最终没有被使用.
From Angular doc: When you provide the service at the root level, Angular creates a single, shared instance of HeroService and injects into any class that asks for it. Registering the provider in the @Injectable metadata also allows Angular to optimize an app by removing the service if it turns out not to be used after all.
还有,
providers: [
// no need to place any providers due to the `providedIn` flag...
]
那么,这是否意味着我们不再需要 CoreModule?我们可以将服务和其他常用模块直接导入到 AppModule 中.
So, does that mean we no more need CoreModule? We can import services and other common modules directly into AppModule.
推荐答案
好吧,我将其视为创建 CoreModule 的替代方案,文档明确指出:
Well I would consider it as an alternative to creating a CoreModule, the documentation clearly states:
在 Angular 中有两种方法可以使服务成为单例:为@Injectable()provideIn 属性的值声明根
There are two ways to make a service a singleton in Angular: Declare root for the value of the @Injectable() providedIn property
将服务包含在 AppModule 或仅由 AppModule 导入的模块中
Include the service in the AppModule or in a module that is only imported by the AppModule
我在这里找到了这个单身服务文档
如果你的应用程序有一个 CoreModule 的纯服务,你可以简单地摆脱它(如果你认为当然没有必要),虽然我不推荐它,对我来说,我认为拥有一个更容易维护CoreModule 因为我可以很容易地在项目中找到它并告诉我哪些服务是应用程序的基础,我们只需要它们中的一个实例,而不必在 IDE 中打开一个搜索对话框并查找所有具有 <代码>providedIn:'root' 设置.
If you app has a CoreModule of pure services you could simply get rid of it(if you don't think is necessary of course), although I don't recommend it, for me I consider it more mantainable to have a CoreModule because I can easily find it in the project and tells me what services are fundamental for the app and we need only one instance from them, instead of having to open a search dialog in the IDE and look for all the services that have the providedIn: 'root'
setted.
这篇关于Angular 6 服务:providIn: 'root' vs CoreModule的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!