I've been watching Angular 2 Getting Started in PluralSight and I saw some Services created are injected in the App Component and Module Component.
Here's example:
When creating a RouterGuard in Angular 2, the created Service for RouterGuard is injected in the Module level but some custom service are injected only to App Component level. My question is, when should I inject a service to Module level and when to inject only to App component level.
Thanks!
Indeed you can provide services at the Module level and at the Component level. You can provide a service at the Module level, by listing it in the providers
array of the NgModule like this:
@NgModule({
declarations: [
...
],
imports: [
...
],
providers: [MyService],
bootstrap: [AppComponent]
})
When you do this, you are providing the same instance across the whole Module and all children.
But, at times, you may want to provide separate instances of services to components. In that case, you can provide a service at the Component level by listing it in the providers
array in the component decorator like this:
@Component({
templateUrl: './app.component.html',
providers: [MyService]
})
This provides a new instance of the service just for this component.
One example of when you want to provide a service at the Module level is when you will use a service to hold data shared by several components. This could be using variables or observables that are stored in the service, but used by several components. Another time you would want to provide a service at the Module level is if your service is stateless(only returns observables from Http calls). In these scenarios, having a shared instance makes sense.
Other times, you may want to provide a service that also holds data, but you want each component to have it's own instance. In this scenario, it makes sense to provide the service at the Component level.
Hope that helps.
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