0 votes
in Angular by
How do you provide a singleton service?

1 Answer

0 votes
by

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.

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root',
    })
    export class MyService {
    }
  2. 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.

    @NgModule({
      ...
      providers: [MyService],
      ...
    })
...