We are just on our first project with angular2. I've got a question about providing a service.
As I know, there are two ways to declare a provider with providers:[MyService]
in your app.
You can declare it globally in the @NgModule
tag or locally in the @Component
tag.
As far as I know, the only difference between the two ways is the providing scope. Once app wide, once only component wide. Out of this I would make the conclusion, that I should prefer to provide a service mostly (depending on the usage of the service) local in my specific component to keep the scope small.
Is that correct, or are there any other differences between the two declaration ways, which I'm not aware of?
This root NgModule is what's used to bootstrap the Angular application. It is in this root module that we also bootstrap the root-level component. This root-level component is the application's main view, which hosts other components for the application. An NgModule is a class adorned with the @NgModule decorator.
Angular distinguishes components from services to increase modularity and reusability. Ideally, a component's job is to enable only the user experience. A component should present properties and methods for data binding to mediate between the view and the application logic.
What is the difference between providers:[ ] and providedIn? Essentially the same thing, just a difference in who tells the service where it should be injected.
When you add a service provider to root module (root injector), it is available for whole application. That means if you have a feature module with service in providers and that service is also provided in root module, in this case both modules will work with the same instance of service (singleton pattern).
If you provide a service local to your components they will NOT have the SAME service. They get all A service of the same type, but they will be not the SAME one.
If you provide them to your AppModule, the will be created as a singleton for the whole app.
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