Is there any design pattern in angular 12 to cancel observable subscriptions?
Currently we are developing an angular app and found out that some of our components does not unsubscribe
to the observable and hence it is causing memory leakage and some weird behavior in different pages. So instead of closing the subscriptions in each component using ngDestroy like for example below, is there a better way like a design pattern that can be reused across the app without changing existing behavior and minimal code as possible?
import {Component, OnInit, Output, EventEmitter, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs';
@Component({ … })
export class ExampleComponent implements OnInit, OnDestroy {
data: any;
private subscription: Subscription;
API: string = 'https://jsonplaceholder.typicode.com/todos/1';
constructor (private http: HttpClient){}
ngOnInit() {
// Subscribed here
this.subscription.add(
this.http.get(this.API).subscribe(
res => {
this.data = res;
} );
)
}
ngOnDestroy() {
// Unsubscribed the subscription
this.subscription.unsubscribe();
}
}
Aucun commentaire:
Enregistrer un commentaire