Angular 6 Services: providedIn: 'root' vs CoreModule

后端 未结 7 903
猫巷女王i
猫巷女王i 2021-02-01 02:40

With Angular 6, below is the preferred way to create singleton services:

import { Injectable } from \'@angular/core\';

@Injectable({
  providedIn: \'root\',
})
         


        
相关标签:
7条回答
  • 2021-02-01 03:35

    Well I would consider it as an alternative to creating a CoreModule, the documentation clearly states:

    There are two ways to make a service a singleton in Angular: Declare root for the value of the @Injectable() providedIn property

    Include the service in the AppModule or in a module that is only imported by the AppModule

    I found this here Singleton Services doc

    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.

    0 讨论(0)
提交回复
热议问题