skip to Main Content
  1. ProviderIn: ‘root’; makes Angular service singleton, and what I understood from word singleton is having one common instance for whole application.

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


  1. 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 angular Dependency injection, so its a responsibility of the user to design to code for it to work between component, Angular use the constructor definition and using inject 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!

    Login or Signup to reply.
  2. The very first sentence in the Angular documentation for singleton services:

    A singleton service is a service for which only one instance exists in an application.
    https://angular.io/guide/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
    Here is more detail from the Angular docs on services.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search