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

后端 未结 6 626
予麋鹿
予麋鹿 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 10:43

    see Excellent explanation by @Nipuna,

    I'd like to extend it by adding examples.

    if you just use Injectable decorator without providedin property, like,

    @Injectable()
    

    then you would have to write service's name in respective Module's providers Array.

    like this;

    data.service.ts ↴

    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class DataService {
        constructor() {}
    
        // Code . . .
    }
    

    app.module.ts ↴

    import { AppComponent } from './app.component';
    import { DataService } from './core/data.service';
    
    @NgModule({
        declarations: [AppComponent],
        providers: [DataService],    // ⟵ LOOK HERE WE PROVIDED IT
        imports: [...],
        bootstrap: [AppComponent],
    })
    export class AppModule {}
    

    But, If you use providedIn: 'root', like this:

    data.service.ts ↴

    import { Injectable } from '@angular/core';
    
    @Injectable({
        providedIn: 'root',
    })
    export class DataService {
        constructor() {}
    
        // Code . . .
    }
    

    Then our module would look like this:

    app.module.ts ↴

    import { AppComponent } from './app.component';
    import { DataService } from './core/data.service';
    
    @NgModule({
        declarations: [AppComponent],
        providers: [],
        imports: [...],
        bootstrap: [AppComponent],
    })
    export class AppModule {}
    

    see I did't add DataService in providers array this time, because it's not needed.

提交回复
热议问题