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:
Let’s discuss these with examples.
领英推荐
import { Injectable } from '@angular/core'
@Injectable({
providedIn: 'root'
})
export class CustomerService {};
import { BrowserModule } from "@angular/platform-browser"
import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
import { CustomerService } from "./customer.service";
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [CustomerService],
bootstrap: [AppComponent]
})
export class AppModule {};
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.
Thanks,
Himanshu M.