What is the purpose of providedIn with the Injectable decorator when generating Services in Angular 6?

后端 未结 6 625
予麋鹿
予麋鹿 2020-12-12 10:06

When generating services in the Angular CLI, it is adding extra metadata with a \'provided in\' property with a default of \'root\' for the Injectable decorator.

<         


        
6条回答
  •  盖世英雄少女心
    2020-12-12 11:02

    From Docs

    What is Injectable decorator?

    Marks a class as available to Injector for creation.

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root',
    })
    export class UserService {
    }
    

    The service itself is a class that the CLI generated and that's decorated with @Injectable().

    What exactly does providedIn do?

    Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in the 'root' injector, which will be the application-level injector in most apps.

    providedIn: Type | 'root' | null
    

    providedIn: 'root'

    When you provide the service at the root level, Angular creates a single, shared instance of service and injects it 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 from the compiled app if it isn't used.

    providedIn: Module

    It's also possible to specify that a service should be provided in a particular @NgModule. For example, if you don't want a service to be available to applications unless they import a module you've created, you can specify that the service should be provided in the module

    import { Injectable } from '@angular/core';
    import { UserModule } from './user.module';
    
    @Injectable({
      providedIn: UserModule,
    })
    export class UserService {
    }
    

    This method is preferred because it enables Tree-shaking (Tree shaking is a step in a build process that removes unused code from a code base) of the service if nothing injects it.

    If it's not possible to specify in the service which module should provide it, you can also declare a provider for the service within the module:

    import { NgModule } from '@angular/core';
    import { UserService } from './user.service';
    
    @NgModule({
      providers: [UserService],
    })
    export class UserModule {
    }
    

提交回复
热议问题