防止 Angular 2 中的内存泄漏? [英] Prevent memory leaks in Angular 2?

查看:28
本文介绍了防止 Angular 2 中的内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Angular 2 中是否有任何关于内存管理的特定陷阱,我应该注意?

In Angular 2 are there any specific pitfalls regarding memory management, I should be aware of?

管理组件状态以避免可能的泄漏的最佳做法是什么?

What are the best practices to manage the state of components in order to avoid possible leaks?

具体来说,我看到有些人在 ngOnDestroy 方法中取消订阅 HTTP observables.我应该总是这样做吗?

Specifically, I've seen some people unsubscribing from HTTP observables in the ngOnDestroy method. Should I always do that?

在 Angular 1.X 中,我知道当 $scope 被销毁时,其上的所有侦听器也会自动销毁.Angular 2 组件中的 observables 怎么样?

In Angular 1.X I know that when a $scope is destroyed, all listeners on it are destroyed as well, automatically. What about observables in Angular 2 components?

@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?
    }
};

推荐答案

根据@katspaugh 的要求

As requested by @katspaugh

在您的特定情况下,无需手动取消订阅,因为这是异步管道的工作.

In your specific case there's no need to unsubscribe manually since that's the Async pipe's job.

检查AsyncPipe 的源代码.为简洁起见,我发布了相关代码

Check the source code for AsyncPipe. For brevity I'm posting the relevant code

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

正如你所看到的,异步管道实现了 OnDestroy,当它被销毁时,它会检查是否有一些订阅并删除它.

As you can see the Async pipe implements OnDestroy, and when it's destroyed it checks if is there some subscription and removes it.

在这种特定情况下,您将重新发明轮子(抱歉,重复我自己).这并不意味着您不能/不应该在任何其他情况下(例如您引用的情况)取消订阅.在这种情况下,用户在组件之间传递 Observable 以进行通信,因此手动取消订阅是一种很好的做法.

You would be reinventing the wheel in this specific case (sorry for repeating myself). This doesn't mean you can't/shouldn't unsubscribe yourself in any other case like the one you referenced. In that case the user is passing the Observable between components to communicate them so it's good practice to unsubscribe manually.

我不知道框架是否可以检测到任何活动订阅并在组件销毁时自动取消订阅,这当然需要更多调查.

I'm not aware of if the framework can detect any alive subscriptions and unsubscribe of them automatically when Components are destroyed, that would require more investigation of course.

我希望这对异步管道有所澄清.

I hope this clarifies a little about Async pipe.

这篇关于防止 Angular 2 中的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆