A singleton service means there is only one shared instance of that service in your app. This helps keep data and logic consistent everywhere you use it.
Singleton service behavior in Angular
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MyService { // service code here }
The providedIn: 'root' option makes Angular create one shared instance for the whole app.
You can inject this service into any component or other service to use the same instance.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CounterService { count = 0; increment() { this.count++; } }
import { Injectable } from '@angular/core'; @Injectable() export class LocalService { data = 'local'; }
Both CounterAComponent and CounterBComponent use the same CounterService instance. Incrementing in one updates the shared count, so both show the same number.
import { Component, Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CounterService { count = 0; increment() { this.count++; } } @Component({ selector: 'app-counter-a', template: `<button (click)="increment()">Increment A</button> Count A: {{counterService.count}}` }) export class CounterAComponent { constructor(public counterService: CounterService) {} increment() { this.counterService.increment(); } } @Component({ selector: 'app-counter-b', template: `<button (click)="increment()">Increment B</button> Count B: {{counterService.count}}` }) export class CounterBComponent { constructor(public counterService: CounterService) {} increment() { this.counterService.increment(); } } @Component({ selector: 'app-root', template: ` <app-counter-a></app-counter-a> <app-counter-b></app-counter-b> ` }) export class AppComponent {}
If you provide a service in a component's providers array, Angular creates a new instance for that component and its children, breaking singleton behavior.
Singleton services are great for shared state but be careful with mutable data to avoid unexpected changes.
Singleton services have one shared instance across the app.
Use providedIn: 'root' to make a service singleton automatically.
Singletons help share data and logic easily between components.