Performance: Why services are needed
This concept affects how efficiently data and logic are shared across components, impacting rendering speed and user interaction responsiveness.
Create a singleton Angular service that fetches data once and shares it via Observables to ComponentA and ComponentB.
ComponentA and ComponentB each fetch the same data independently inside ngOnInit() without a shared service.| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Duplicate data fetching in components | Multiple redundant DOM updates | Multiple reflows due to repeated change detection | Higher paint cost from frequent updates | [X] Bad |
| Shared data via singleton service | Minimal DOM updates triggered by shared Observables | Single reflow per data change | Lower paint cost due to fewer updates | [OK] Good |
export class CounterService {
count = 0;
increment() { this.count++; }
}
@Component({ selector: 'app-one', template: '' })
export class OneComponent {
constructor(private counter: CounterService) {}
ngOnInit() { this.counter.increment(); console.log(this.counter.count); }
}
@Component({ selector: 'app-two', template: '' })
export class TwoComponent {
constructor(private counter: CounterService) {}
ngOnInit() { this.counter.increment(); console.log(this.counter.count); }
}@Injectable({ providedIn: 'root' })
export class DataService {
data = [];
}
@Component({ selector: 'app-test', template: '' })
export class TestComponent {
dataService: DataService;
constructor(private dataService: DataService) {
}
}Pass the test and this pattern moves unknown