取消订阅的最简单方法Angular

取消订阅的最简单方法Angular

本文介绍了取消订阅的最简单方法Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

他对Angular非常陌生.我大约有4个数据库查询,每个查询都是 Subscriptions(rxjs/Rx).因此,我知道我需要取消订阅每个订阅以节省内存泄漏.如何优化通话?我的意思是,我不想调用每个订阅并逐个取消订阅.我想在一次通话中完成所有取消订阅的操作.抱歉,这是一个愚蠢的问题.有主意吗?预先感谢

Hi am very new to Angular. I have around 4 database queries and each of them are Subscriptions(rxjs/Rx). So I know I need to unsubscribe each of my subscriptions to save memory leakage. How can I optimise the calling? I mean, I don't want to call each subscription and unsubscribe one by one. I wanna do it all the unsubscribe in one call. Sorry if its a stupid question. Any idea guys? Thanks in advance

推荐答案

subscriptions = Subscription[];

someMethod() {
  this.subscriptions.push(http.get(...).map(...).subscribe(...));
}

ngOnDestroy() {
  this.subscriptions.forEach(s => s.unsubscribe());
}

可观察对象完成后,退订是多余的.取消订阅仅对于持续发出事件但未完成的可观察对象是必需的.

When an observable completes, unsubscribing is redundant. Unsubscribing is only necessary for observables that continueally emit events without completing.

如果您只想接收一个事件(或事件数量有限),则可以使用 take(x)这样的运算符控制订阅的可观察对象的完成时间,然后在 x 事件将完成.

If you only want to receive a single (or otherwise limited number of events) you can control when the observable you subscribed to completes by using an operator like take(x), then after x events the observable will complete.

这篇关于取消订阅的最简单方法Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 19:20