Prevent memory leak in Angular 2?

In Angular 2, are there any specific memory management issues I should know?

What are the best practices for managing component health to avoid potential leaks?

In particular, I saw some HTTP-observable failures in the ngOnDestroy method. Should I always do this?

In Angular 1.X, I know that when a $scope destroyed, all listeners on it are also destroyed automatically. What about the components observed in Angular 2?

 @Component({ selector: 'library', template: ` <tr *ngFor="#book of books | async"> <td>{{ book.title.text }}</td> <td>{{ book.author.text }}</td> </tr> ` }) export class Library { books: Observable<any>; constructor(private backend: Backend) { this.books = this.backend.get('/texts'); // <-- does it get destroyed // with the component? } }; 
+15
javascript angularjs memory-leaks angular rxjs
Dec 25 '15 at 9:56
source share
1 answer

As requested by @katspaugh

In your particular case, there is no need to manually cancel the subscription, as this is an Async job.

Check out the source code for AsyncPipe. For brevity, I send the appropriate code

 class AsyncPipe implements PipeTransform, OnDestroy { // ... ngOnDestroy(): void { if (isPresent(this._subscription)) { this._dispose(); } } 

As you can see, the Async channel implements OnDestroy, and when it is destroyed, it checks to see if there is any subscription and deletes it.

You would invent the wheel in this particular case (sorry for repeating yourself). This does not mean that you cannot / should not unsubscribe yourself in any other case, like the one you referred to. In this case, the user passes the Observable between the components to inform them, so it’s good practice to manually cancel the subscription.

I do not know if the framework will be able to detect any live subscriptions and automatically unsubscribe them when the Components are destroyed, which will require more study.

Hope this clarifies a bit about the Async pipe.

+12
Dec 27 '15 at 18:14
source share



All Articles