Performance: Service-based state management
This affects how efficiently the app updates UI and handles user interactions by centralizing state in services.
Jump into concepts and practice - no test required
Use a singleton Angular service with RxJS BehaviorSubject to hold and emit state changes to all components.
Each component maintains its own local state and uses @Input/@Output to pass data up and down the tree.
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Local state in each component with @Input/@Output | Many duplicated DOM updates across components | Multiple reflows triggered per update | High paint cost due to redundant updates | [X] Bad |
| Centralized service state with RxJS and async pipe | Single DOM update per state change | Single reflow per update | Low paint cost with targeted updates | [OK] Good |
increment() twice?import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CounterService {
count = signal(0);
increment() {
this.count.update(c => c + 1);
}
}
const service = new CounterService();
service.increment();
service.increment();
console.log(service.count());import { Injectable, signal } from '@angular/core';
@Injectable()
export class DataService {
data = signal([]);
addItem(item: string) {
this.data().push(item);
}
}import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class TaskService {
tasks = signal([]);
addTask(newTask: string) {
// Which line correctly updates tasks?
}
}