Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference in Angular2 between inject a provider in @Component and @Module?

Tags:

angular

In angular2 it is possible to define the providers in a @Component element like

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers : [ DataService ]
})
export class HomeComponent implements OnInit {

...
}

and also in a

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [ DataService ],
  bootstrap: [AppComponent ]
})
export class AppModule { }

what is the difference between define the provider in the @NgModule or in a @Component? and If I should choose one of two, what should be the better place to define the provider ?

like image 266
Pablo Ezequiel Inchausti Avatar asked Dec 03 '22 13:12

Pablo Ezequiel Inchausti


1 Answers

Angular application is a tree of components. Each component has its own injector. Hence, you have a tree of injectors. Suppose, you have the following setup:

    AppComponent
  /            \
 C1            C2
              /  \
            C3   C4

Now, if you define a provider inside any @NgModule (except the one this is lazy loaded), you'll be able to access that provider in any of the components (C1, C2, C3, C4). If you define a provider in @Component, say in C2, only C2 and its children C2 will be able to access that provider. But even this is configurable. You can use additional decorators like @Self to search for a dependency declared by the component.

like image 154
Max Koretskyi Avatar answered Feb 15 '23 22:02

Max Koretskyi