0
0
Angularframework~5 mins

Singleton service behavior in Angular

Choose your learning style9 modes available
Introduction

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.

When you want to share data or state across multiple components.
When you need a single source of truth for settings or user info.
When you want to avoid creating multiple copies of a service to save memory.
When you want to centralize business logic that many parts of your app use.
Syntax
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.

Examples
This service keeps a count number that all components share.
Angular
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CounterService {
  count = 0;

  increment() {
    this.count++;
  }
}
This service is not singleton by default. You must provide it in a component or module to create separate instances.
Angular
import { Injectable } from '@angular/core';

@Injectable()
export class LocalService {
  data = 'local';
}
Sample Program

Both CounterAComponent and CounterBComponent use the same CounterService instance. Incrementing in one updates the shared count, so both show the same number.

Angular
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 {}
OutputSuccess
Important Notes

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.

Summary

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.