且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rxjs可观察生命周期

更新时间:2023-01-25 17:25:33

Observable 上调用.subscribe(...)会返回 Subscription .

如果您不将此预订分配给变量(或者将其推送到预订数组),则将丢失对该预订的引用,因此您无法取消订阅该预订,这可能导致内存泄漏

If you don't assign this subscription to a variable (or in your case push it to an array of subscriptions), you will lose reference to this subscription, hence you can't unsubscribe from it, which can cause memory leaks.

因此,您假设将其推送到订阅数组中:

So your assumption of pushing it into array of subscriptions:

this.subscriptions.push(this.myService.myObservable.subscribe(...));

并取消订阅组件的 ngOnDestroy 是正确的.

and unsubscribing in ngOnDestroy of your component is correct.