Reputation: 817
I would like to have some explanations about singleton services in Angular2. I made a quick example in a plnkr : http://plnkr.co/edit/09XVxN?p=preview
Try to change the displayed component by clicking on both buttons. You will see in the debugger console ServiceA
constructor console.log
messages.
Why AService
in this case isn't a singleton ? Because each time we switch the displayed component it calls the AService
constructor...
Thanks by advance
Upvotes: 2
Views: 498
Reputation: 658047
Since Angular 9
Use @Injectable({ providedIn: 'root' })
With providedIn: '...'
the service will discovered by the Angular compiler. It is then not necessary to add the service to providers anymore.
https://angular.io/guide/providers
Original answer
When you add a service to the providers:
list of a component you get a new instance for every component.
Add it only to bootstrap(AppComponent, [AService])
and the whole application gets the same reference.
In Angulars DI every provided instance is a singleton, but only within the scope of the injector that created the instance.
Angulars DI is hierarchical. For each component a child-injector is created. DI starts with the closest injector to resolve the required type. If there is a provider but no instance yet, one will created. If there is no provider DI iterates to the parent injector until it finds one or until it reaches the root injector. If it reached the root injector and still didn't find a provider it throws.
The providers added to bootstrap()
are the providers for the root injector and therefore applicable for the whole application when not further down the hierarchy another injector has a provider for the same type registered.
Upvotes: 1
Reputation: 202316
In fact, it depends on where you put the corresponding providers:
If you put it at the bootstrap level, you'll have a single instance for the whole application
bootstrap(AppComponent, [ MyService ]);
If you put it at the component level, you'll have an instance for each component instance.
@Component({
(...)
providers: [ MyService ]
})
export class MyComponent {
(...)
}
This is because of the hierarchical injectors of Angular2. You can make a bit finer since it's possible to use providers from parent component as well...
This answer could give you more details about this:
Upvotes: 1