Angular question detail
How do you provide a singleton service?
There are two possible ways to provide a singleton service.
- 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 {
}
- 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],
...
})