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?
18 hours ago in Node-js by Nidhi
• 12,380 points
13 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 17 hours ago 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,698 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,788 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,031 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,317 views
0 votes
1 answer

How to use interceptors to modify HTTP requests and responses in Angular?

In Angular, interceptors are used to modify ...READ MORE

answered 17 hours ago in Node-js by Anvi
15 views
0 votes
1 answer
0 votes
1 answer

How to create a simple React Element displaying "Hello, World!"?

You can create a simple React element ...READ MORE

answered 17 hours ago in Node-js by Anvi
13 views
0 votes
1 answer

How to use the render function to display a React component?

To display a React component, use the ...READ MORE

answered 17 hours ago in Node-js by Anvi
12 views
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
105 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