-
ProviderIn: ‘root’; makes Angular service singleton, and what I understood from word singleton is having one common instance for whole application.
-
If I instantiate that service in constructor of two components(creating an object from a class) that means I am crating 2 diff object, it contradict the first statement.
Can someone please explain me what singleton means in this scenario?
2
Answers
Angular use DI (Dependency Injection) to provide services to you, there is no need to instantiate any Services.
The
providedIn: 'root'
creates a singleton of a class for the entire application.If you want to add a service which is a singleton only for a module, you add it to the providers array of the module or component or standalone component
When you instantiate your own class (
this.classVar = new Test();
) like this, this is not under the scope of angularDependency injection
, so its a responsibility of the user to design to code for it to work between component, Angular use the constructor definition and usinginject
to provide the user with the desired service when requested by the user.When the user instantiated their own class, it is the user’s responsibility of taking care of instances, so angular is working as per the rules!
The very first sentence in the Angular documentation for singleton services:
Referencing a service in your constructor does not instantiate a new instance of the service (unless none exists). More on this in the services documentation. https://angular.io/guide/architecture-services