在对我当前的 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/