Angular Services

Providing a singleton service

Two ways to make a service singleton in Angular

  • Declare that the service should be provided in the application root.
  • Include the service in the AppModule or in a module that is only imported by the AppModule.

Beginning with Angular 6.0, the preferred way to create a singleton services is to specify on the service that it should be provided in the application root. This is done by setting providedIn to root on the service’s @Injectable decorator:

Prefered Angular 6 Way using @Injectable decorator

  • Angular creates a single, shared instance of service and injects into any class that asks for it.
  • Registering the provider in the @Injectable metadata also allows Angular to optimize an app by removing the service if it turns out not to be used after all.
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class VoteService {
}

Register Service in providers array of @NgModule

import {VoteService} from './vote.service';
...
@NgModule({
  imports:      [ BrowserModule],
  declarations: [ AppComponent],
  bootstrap:    [ AppComponent],
  providers: [VoteService]
})

Reference

2 thoughts on “Angular Services”

Leave a Reply

Your email address will not be published. Required fields are marked *