Angular 6服务:providerIn:'root'与CoreModule [英] Angular 6 Services: providedIn: 'root' vs CoreModule

查看:146
本文介绍了Angular 6服务:providerIn:'root'与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.

推荐答案

文档中明确指出:

在Angular中有两种使服务成为单例的方法: 声明根以提供@Injectable()提供的属性的值

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服务:providerIn:'root'与CoreModule的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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