Prompt Title: Unsubscribing in TypeScript

Created 2 years ago
Votes 0
Views 400 times
0

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:

kotlin
import { 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.

avatar
zvis
Shared 1 prompt
Created 2 years ago

Leave a Comment

Related Tag Prompts

0
0
Rejection for Position.
2 years ago 2023-03-11 17:25:32 Fiber