Performance: Observable in component lifecycle
This affects interaction responsiveness and memory usage during component lifecycle events.
subscription = new Subscription(); ngOnInit() { this.subscription.add( this.dataService.getData().subscribe(data => { this.data = data; }) ); } ngOnDestroy() { this.subscription.unsubscribe(); }
ngOnInit() {
this.dataService.getData().subscribe(data => {
this.data = data;
});
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Subscribe without unsubscribe | No direct DOM ops but triggers repeated change detection | Multiple reflows if data updates frequently | High paint cost due to unnecessary updates | [X] Bad |
| Subscribe with unsubscribe on destroy | Minimal DOM ops triggered only on relevant data changes | Single or minimal reflows | Lower paint cost due to controlled updates | [OK] Good |
ngOnInit lifecycle hook in an Angular component?ngOnInit rolengOnInit runs once when the component is created, ideal to start tasks like subscribing to Observables.ngOnInitngOnDestroy lifecycle hook?unsubscribe() method to stop listening to Observables.ngOnDestroy, calling unsubscribe() properly cleans up the subscription.export class TimerComponent implements OnInit, OnDestroy {
time = 0;
private subscription!: Subscription;
ngOnInit() {
this.subscription = interval(1000).subscribe(() => {
this.time++;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}time after 3 seconds if the component is displayed and then removed?interval(1000) emits a value every 1000 milliseconds (1 second), triggering the subscription callback.time from 0 to 3. The unsubscribe in ngOnDestroy stops further increments.export class DataComponent implements OnInit {
data$ = this.service.getData();
ngOnInit() {
this.data$.subscribe(data => {
console.log(data);
});
}
}ngOnDestroy to unsubscribe, the subscription stays active even after component destruction.ngOnInit ensures the component starts listening after creation.ngOnDestroy to prevent leaksPass the test and this pattern moves unknown