Reputation: 4449
What can cause memory leaks in Angular2 (rc5) application? How to prevent them?
Wrong/correct code examples would be much appreciated.
Upvotes: 17
Views: 13512
Reputation: 1434
The subscribe and unsubscribe aspect that @BeetleJuice mentioned above is certainly the No.1 precaution we need to keep in mind to prevent memory leak.
To have better understanding of some the memory management techniques, you can look at Memory management in Angular applications. (Notes that you can find the exact same article in multiple site. Copyright issue here and there? )
There is one thing that I would like to say about the "Event listeners" in particular. Over a recent project that I have done, I use Event emitter and listeners for child components to talk to parent components. I specially stick to one rule:
Parent components listen to only DIRECT child components.
Here parent components are acting as container components and child components are acting as presentational components.
This way I can make sure whenever I remove a child component, there is only one spot, which is the direct parent, to remove all its listeners. So far, this rule works pretty good for me.
Upvotes: 0
Reputation: 40936
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(); }
we must unsubscribe before Angular destroys the component. Failure to do so could create a memory leak.
Upvotes: 16