A note on providers

Before @NgModule was introduced, Angular applications and especially components were thought to be responsible for what they needed. Therefore, it was commonplace for a component to ask for what dependencies it needed in order to be instantiated correctly. In the example of the previous section, the MusicPlayerComponent asks for a Playlist dependency. While this is still technically possible to do, we should use our new @NgModule concept and provide constructs on a module level instead. This means that the previously mentioned example would instead register its dependencies in a module, like so:

@NgModule({
declarations: [MusicComponent, MusicPlayerComponent]
providers: [Playlist, SomeOtherService]
})

Here, we can see that Playlist and SomeOtherService would be available for injection, for all constructs declared in the declarations property. As you can see, the responsibility of where to provide a service has shifted somewhat. As mentioned before, this does not mean we can't provide constructs on a per component level, there exist use cases where this makes sense. We want to stress however that the normal case is to place your services or other constructs, which need injecting, in the providers property of the module rather than the component.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset