Angular 6 Services: providedIn: 'root' vs CoreModule

后端 未结 7 901
猫巷女王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:21

    When Angular engine starts initiating a component, and you have declared services in your constructor, angular tries to pass the instances of the declared services to the component. So angular should somehow know where can be taken instances, there is a point where providers array comes.

    When you declare needed services without providedin: core pair, we create non singleton instance of the service. which means that, when angular destroys component, services declared in the component will be destroyed too.

    As mentioned before, there are two ways to declare application level singleton services: 1. declare them into providers of related module; 2. declare them into providers of a component with providedIn: core pair.

    also interesting note about @Injectable decorator. this is only required when service injects another service. for example if you inject http service in your service, you have to add @Injecrable decorator.

    this is how dependency injection works.

提交回复
热议问题