InterviewHubPRO
Section Overview
Q235

Question 235 of 283

Part 9: NgModules, Providers, NgZone & Injector Hierarchies (213 - 255)

83%
Angular & Signals (283 Qs)•Part 9: NgModules, Providers, NgZone & Injector Hierarchies (213 - 255)

How do you provide a singleton service?

There are two possible ways to provide a singleton service.

  1. Set the providedIn property of the @Injectable() to "root". This is the preferred way(starting from Angular 6.0) of creating a singleton service since it makes your services tree-shakable.
js
  import { Injectable } from '@angular/core';

  @Injectable({
    providedIn: 'root',
  })
  export class MyService {
  }
  1. Include the service in root module or in a module that is only imported by root module. It has been used to register services before Angular 6.0.
js
  @NgModule({
    ...
    providers: [MyService],
    ...
  })