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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With