6

Making Angular Service – Always  Singleton – Dhananjay Kumar

 1 year ago
source link: https://debugmode.net/2022/08/10/making-angular-service-always-singleton/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Making Angular Service – Always  Singleton

By default, Angular Services are Singleton. When you create a service using the CLI command,

ng g s App

Angular creates a service named AppService.

The above service is

  1. Singleton
  2. Tree-shakeable
  3. Available throughout the application

Singleton means Angular creates only one object of the AppService, regardless of how many places you use it. However, if you re-provide the service in another component or a module and use it inside, Angular will create separate objects for them.

As shown below , if you again provide the AppService in ProductComponent; Angular creates a new object of the AppService, and provides it to the ProductComponent and all its child components.

Sometimes you may have a requirement to prevent a service from being instantiated more than once. As you have seen that if you re-provide a service, Angular creates a new object of that. You can prevent this, as shown.

To prevent a service to be re provided and getting more than one objects being created,  you can create a injector guard.

After creating injector, modify the service as shown below.

Basically, to make a service singleton, extends the guard and in the constructor of the service, pass the service class to the guard.

Now when you re-provide the AppService, Angular will throw you error, as shown below

image.png?w=904

I hope you find this post useful and now should be able to use it in your project and answer in interview.  Thanks for reading.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK