Performance: Singleton service behavior
This affects the memory usage and initialization time of services shared across components, impacting interaction responsiveness and load speed.
import { Injectable, Component } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { data = []; constructor() { console.log('Singleton service created'); } } @Component({ selector: 'app-comp1', template: '<p>Component 1</p>' }) export class Comp1 { constructor(public dataService: DataService) {} } @Component({ selector: 'app-comp2', template: '<p>Component 2</p>' }) export class Comp2 { constructor(public dataService: DataService) {} }
import { Injectable, Component } from '@angular/core'; @Injectable() export class DataService { data = []; constructor() { console.log('Service created'); } } @Component({ selector: 'app-comp1', providers: [DataService], template: '<p>Component 1</p>' }) export class Comp1 { constructor(public dataService: DataService) {} } @Component({ selector: 'app-comp2', providers: [DataService], template: '<p>Component 2</p>' }) export class Comp2 { constructor(public dataService: DataService) {} }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Multiple service instances (component providers) | No direct DOM impact | No reflows | No paint cost | [X] Bad |
| Singleton service (providedIn: 'root') | No direct DOM impact | No reflows | No paint cost | [OK] Good |
singleton?providedIn: 'root' to provide a singleton service at the app root level.export class CounterService {
count = 0;
increment() { this.count++; }
getCount() { return this.count; }
}increment() once. What will getCount() return when called from either component?count variable.increment() once, so total increments = 2.@Injectable() but forgot to add providedIn: 'root'. What problem will occur when multiple components inject this service?providedIn: 'root', Angular does not provide the service globally.providedIn: 'root' makes the service singleton app-wide.Pass the test and this pattern moves unknown