Complete the code to unsubscribe from the observable in ngOnDestroy.
export class MyComponent implements OnDestroy { subscription = this.dataService.getData().subscribe(); ngOnDestroy() { this.subscription.[1](); } }
To avoid memory leaks, you must call unsubscribe() on your subscription when the component is destroyed.
Complete the code to use the takeUntil operator to manage unsubscription.
private destroy$ = new Subject<void>();
ngOnInit() {
this.dataService.getData()
.pipe([1](this.destroy$))
.subscribe(data => this.handleData(data));
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}The takeUntil operator unsubscribes automatically when the destroy$ emits, helping prevent memory leaks.
Fix the error in the code to properly unsubscribe from multiple subscriptions.
export class MyComponent implements OnDestroy { sub1 = this.service.getData1().subscribe(); sub2 = this.service.getData2().subscribe(); ngOnDestroy() { this.sub1.[1](); this.sub2.[1](); } }
Each subscription must be unsubscribed individually by calling unsubscribe() on them.
Fill both blanks to create a single Subscription to manage multiple subscriptions and unsubscribe properly.
export class MyComponent implements OnDestroy { private subscriptions = new Subscription(); ngOnInit() { this.subscriptions.add(this.service.getData1().subscribe()); this.subscriptions.add(this.service.getData2().subscribe()); } ngOnDestroy() { this.subscriptions.[1](); this.subscriptions = [2]; } }
Calling unsubscribe() on the combined subscription stops all inner subscriptions. Then resetting it to a new Subscription avoids reuse issues.
Fill all three blanks to correctly use the async pipe in the template and avoid manual unsubscription.
<div *ngIf="data$ | [1] as data"> <p>{{data.name}}</p> </div> export class MyComponent { data$ = this.service.getData().[2](); ngOnDestroy() { // No manual unsubscription needed because of [3] } }
The async pipe in the template automatically subscribes and unsubscribes from observables, so manual unsubscription in ngOnDestroy is not needed.