ngOnDestroy lifecycle hook in this component?The ngOnDestroy hook is called just before Angular destroys the component. It is used to clean up resources like subscriptions to avoid memory leaks.
this.sub. Which option correctly unsubscribes in ngOnDestroy?export class MyComponent implements OnDestroy { sub = this.dataService.getData().subscribe(); ngOnDestroy() { // What goes here? } }
The unsubscribe() method stops the subscription and frees resources. Other methods like close(), stop(), or cancel() do not exist on subscriptions.
export class LeakComponent implements OnDestroy { sub = this.dataService.getData().subscribe(data => { console.log(data); }); ngOnDestroy() { // No cleanup here } }
Not unsubscribing from subscriptions causes them to stay active, holding memory and causing leaks. Logging data or missing OnInit does not cause leaks.
Using a Subscription container (like new Subscription()) to add all subscriptions and then calling unsubscribe once is cleaner and less error-prone.
export class TimerComponent implements OnDestroy { count = 0; intervalId = setInterval(() => { this.count++; console.log('Count:', this.count); }, 1000); ngOnDestroy() { clearInterval(this.intervalId); console.log('Cleanup done'); } } // Assume component is destroyed after 3500ms
The interval runs every 1000ms. After 3500ms, three counts have logged (at 1000, 2000, 3000 ms). Then ngOnDestroy clears the interval and logs "Cleanup done".