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