Creating a Singleton service in Angular
Photo by Mike Meyers on Unsplash

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

import { Injectable } from '@angular/core'


@Injectable({

  providedIn: 'root'

})

export class CustomerService {};        


  • 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:-

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.

要查看或添加评论,请登录

Himanshu Motwani的更多文章

  • Global usings in C#

    Global usings in C#

    C# has a lot of in-built libraries which we call DLLs or Dynamic Link Library also it provides you as a developer the…

社区洞察

其他会员也浏览了