Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leaks in Angular2

What can cause memory leaks in Angular2 (rc5) application? How to prevent them?

Wrong/correct code examples would be much appreciated.

like image 221
chriss Avatar asked Aug 18 '16 06:08

chriss


People also ask

How do you find memory leaks in angular 2?

The first thing to do is to open the Chrome Dev Tools, open the panel on the right and click on More Tools > Performance Monitor. The memory of our application is displayed in the blue graph.

What are memory leaks in angular?

JS heap size Heaps in JavaScript are long lived objects, the difference between objects created and deleted. Heaps appear when memory leaks occur. A memory leak is when an object in a program is still consuming memory assigned to it after the code has been read, and the object assessed.


1 Answers

In the browser, Angular is just JavaScript, so the typical caveats apply.

One thing that Angular specifically warns against though is Observables. Once you subscribe to one, it will keep working until you unsubscribe, even if you navigate to another view. Angular unusbscribes for you where possible (eg if you use the async pipe in the template:

model

//listenToServer returns an observable that keeps emitting updates
serverMsgs = httpService.listenToServer();

template

<div>{{serverMsgs | async}}</div>

Angular will show server messages in the div, but end the subscription when you navigate away.

However, if you subscribe yourself, you have to also unsubscribe:

model

msgs$ = httpService.listenToServer().subscribe(
    msg => {this.serverMsgs.push(msg); console.log(msg)}
);

template

<div *ngFor="let msg of serverMsgs">{{msg}}</div>

When you navigate away, even though you cannot see new messages appear in the view, you will see them printed to the console as they arrive. To unsubscribe when the component is disposed of, you would do:

ngOnDestroy(){ this.msgs$.unsubscribe(); }

From the docs:

we must unsubscribe before Angular destroys the component. Failure to do so could create a memory leak.

like image 132
BeetleJuice Avatar answered Oct 11 '22 10:10

BeetleJuice