Creating a Singleton service in Angular
Angular services come into the picture when you need to call an API to fetch some data from Server in your front-end application OR you need to maintain some data in the angular application which can be reused by different components of your application OR you want to retrieve some data from your local cache server.
In Angular, the services can be a singleton or non-singleton.
Singleton service is a service whose only one instance is shared amongst the whole application.
Providing a singleton service
There are two basic ways to make a service a singleton in Angular:
- Set the providedIn property of the @Injectable to “root”
- Include the service in the AppModule or in a module that is only imported by the AppModule
Let’s discuss these with examples.
- Using “providedIn” property:- With Angular 6.0, setting providedIn property is the preferred way to mark a service singleton. The developer just need to set providedIn to root on the service's @Injectable decorator. This tells Angular to provide the service in the application root. If we take an example to depict this:-
- Setting up in “NgModules providers” array:- In applications built with Angular versions prior to 6.0, services are registered in NgModule providers arrays as follows:-
Here, the NgModule is the root module hence the CustomerService will act as a Singleton service because only one instance of this service will be shared across the application.
You might have noticed that using the first approach i.e. setting providedIn property is a much more convenient way and also a developer who is new to the application will be able to know the Singleton nature of this service just by reading the service file.
Hope you’ve learned something new today by reading this article.