angular - angular2 中的管道是否有销毁 Hook (与组件相同)?

标签 angular observable

在对我当前的 Angular2 应用程序的巨大内存泄漏进行了数天(!?!)调查之后,我有了新的发现:

显然,在整个应用程序中大量使用的异步管道正在订阅一个可观察对象,但在清理组件和管道时从未被释放(取消订阅)。

对于单个可观察对象,用户操作非常少(最终导致应用程序崩溃),它积累了大约 11,000 个观察者。

我需要取消订阅可观察对象,为此我需要一个销毁钩子(Hook),类似于 ngOnDestroy,但用于管道。

有没有这样的钩子(Hook),如果没有,你会建议如何退订?

最佳答案

如果你看一下 async pipe代码,您可以看到它们正在使用 ngOnDestroy,就像您在指令中使用它一样。

AsyncPipe 代码片段:

@Pipe({name: 'async', pure: false})
@Injectable()
export class AsyncPipe implements OnDestroy {
  ...

  ngOnDestroy(): void {
    if (isPresent(this._subscription)) {
      this._dispose();
    }
  }
  ...
}

关键是使用:pure:false,

来自 OnDestroy

To create a stateful Pipe, you should implement this interface and set the pure parameter to false in the PipeMetadata.

A stateful pipe may produce different output, given the same input. It is likely that a stateful pipe may contain state that should be cleaned up when a binding is destroyed. For example, a subscription to a stream of data may need to be disposed, or an interval may need to be cleared.

关于angular - angular2 中的管道是否有销毁 Hook (与组件相同)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37578834/

相关文章:

javascript - 如何使用 ngx-pagination 在 ionic4 应用程序中对数据进行分页?

node.js - 从 Angular2 到 Electron 并返回的最佳通信方式是什么?

javascript - 通过服务从 json 文件中获取数据在 Angular4 中给出 "unexpected end of input"

angular - 循环数组并为 Observable 中的每个 id 返回数据

angular - 是什么导致可观察到的返回结果和在浏览器中显示结果之间的滞后?

javascript - 如何在 Javascript 中将字符串数组转换为特定的树结构

css - Angular 2 在时间间隔内改变组件 - 组件轮播(不是图像)

angular - 如何在测试 angular2 组件时模拟可观察流?

swift - 将事件绑定(bind)到 Observable<JSON> 的键

javascript - 使用 Angular 6 中的 Observable 捕获 Promise 拒绝错误