Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between providing a service to NgModule vs Component

Tags:

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?

like image 400
Herr Derb Avatar asked Sep 23 '16 08:09

Herr Derb


People also ask

What is the difference between NgModule and component?

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.

What is difference between component and service in Angular?

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 providedIn and providers in Angular?

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 the root application injector its available?

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).


1 Answers

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.

like image 143
slaesh Avatar answered Sep 24 '22 16:09

slaesh