What can cause memory leaks in Angular2 (rc5) application? How to prevent them?
Wrong/correct code examples would be much appreciated.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With