How to unsubscribe from an observable to prevent memory leaks in Angular

0 votes
Can i know How to unsubscribe from an observable to prevent memory leaks in Angular?
Mar 21 in Node-js by Nidhi
• 12,580 points
44 views

1 answer to this question.

0 votes

In Angular, unsubscribe from observables to prevent memory leaks by:

1. Manual Unsubscribe:

subscription: Subscription;

ngOnInit() {

  this.subscription = this.myService.getData().subscribe(data => { /* ... */ });

}

ngOnDestroy() {

  this.subscription.unsubscribe();

}

2. Using takeUntil:

destroy$ = new Subject<void>();

ngOnInit() {

  this.myService.getData()

    .pipe(takeUntil(this.destroy$))

    .subscribe(data => { /* ... */ });

}

ngOnDestroy() {

  this.destroy$.next();

  this.destroy$.complete();

}

3. Using async pipe (auto-unsubscribes):

<div *ngIf="data$ | async as data">{{ data }}</div>

answered Mar 21 by Anvi

Related Questions In Node-js

0 votes
1 answer

How to use executables from a package installed locally in node_modules?

Hello @kartik, Use the npm bin command to get the ...READ MORE

answered Jul 13, 2020 in Node-js by Niroj
• 82,840 points
1,712 views
0 votes
1 answer

How to write a test which expects an Error to be thrown in Jasmine?

Hello @kartik, Try using an anonymous function instead: expect( ...READ MORE

answered Jul 13, 2020 in Node-js by Niroj
• 82,840 points
9,805 views
0 votes
1 answer

How to create an HTTPS server in Node.js?

Hello @kartik, The minimal setup for an HTTPS ...READ MORE

answered Jul 13, 2020 in Node-js by Niroj
• 82,840 points
2,036 views
0 votes
1 answer

How to execute an external program from within Node.js?

Hello @kartik, Exec has memory limitation of buffer ...READ MORE

answered Jul 17, 2020 in Node-js by Niroj
• 82,840 points
4,332 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to declare an array in TypeScript?

In TypeScript, arrays can be declared in ...READ MORE

answered Dec 17, 2024 in Node-js by Navya
110 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP