Singleton Service in Angular: What It Is and How It Works
singleton service in Angular is a service that is created once and shared across the entire app. It provides a single instance that all components and other services can use to share data or logic consistently.How It Works
Think of a singleton service like a single shared notebook that everyone in a group uses to write and read notes. Instead of each person having their own notebook, everyone accesses the same one, so the information stays consistent.
In Angular, when you provide a service at the root level (using providedIn: 'root'), Angular creates one instance of that service for the whole app. This instance lives as long as the app runs, so any component or service that asks for it gets the same copy.
This means data or functions inside the singleton service are shared and synchronized across different parts of your app without needing to pass data manually between components.
Example
This example shows a simple singleton service that stores a user's name and shares it between two components.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class UserService { private userName = ''; setUserName(name: string) { this.userName = name; } getUserName(): string { return this.userName; } } // Component A import { Component } from '@angular/core'; import { UserService } from './user.service'; @Component({ selector: 'app-component-a', template: `<input (input)="updateName($event.target.value)" placeholder="Enter name" />` }) export class ComponentA { constructor(private userService: UserService) {} updateName(name: string) { this.userService.setUserName(name); } } // Component B import { Component, OnInit } from '@angular/core'; import { UserService } from './user.service'; @Component({ selector: 'app-component-b', template: `<p>User name is: {{ userName }}</p>` }) export class ComponentB implements OnInit { userName = ''; constructor(private userService: UserService) {} ngOnInit() { this.userName = this.userService.getUserName(); } }
When to Use
Use a singleton service when you want to share data or logic across many parts of your Angular app without duplicating it. For example:
- Sharing user login status or profile info
- Managing app-wide settings or themes
- Storing data fetched from a server to avoid repeated requests
- Coordinating communication between unrelated components
Singleton services help keep your app organized and efficient by centralizing shared state and behavior.
Key Points
- A singleton service is created once and reused everywhere in the app.
- Providing a service with
providedIn: 'root'makes it a singleton automatically. - Singleton services help share data and logic without passing inputs and outputs between components.
- They live as long as the app runs, keeping state consistent.
Key Takeaways
providedIn: 'root' to make a service singleton automatically.