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.

    import { Injectable } from '@angular/core';
    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.

    providers: [MyService],

June 06, 2022