Prompt Detail:
Yes, you can keep track of all the Subscription
objects in your component and then unsubscribe from them in the ngOnDestroy
method. Here's an example:
kotlinimport { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnDestroy {
private subscriptions: Subscription[] = [];
constructor(private myService: MyService) {
this.subscriptions.push(this.myService.observable1.subscribe());
this.subscriptions.push(this.myService.observable2.subscribe());
this.subscriptions.push(this.myService.observable3.subscribe());
}
ngOnDestroy() {
this.subscriptions.forEach(sub => sub.unsubscribe());
}
}
In this example, the MyComponent
class keeps track of all the Subscription
objects by pushing them into an array called subscriptions
. In the ngOnDestroy
method, we loop through all the Subscription
objects in the array and unsubscribe from them using the unsubscribe()
method.
Add a comment