[英]How to move subscription logic from ngOnInit to ngOnChange
這是一個關於 Angular 的更一般的問題 - 我對它很陌生 - 是一個徹頭徹尾的 React 書呆子。
我的任務是將邏輯移動到 ngOnChanges,涵蓋我們應該訂閱、保留現有訂閱或取消訂閱的每種情況。 我怎么做?
這是一些示例代碼:
ngOnInit() {
const obsValue$ = combineLatest([
this.store.pipe(select(this.example1Selector.getData())),
this.store.pipe(select(this.example2Selector.getData()))
]).pipe(
tap(([important1, important2]) => {
this.important1 = important1;
this.important2 = important2;
})
);
}
我想將此代碼移動到 ngOnChange 並僅在需要時訂閱並在必要時保留它並在必要時取消訂閱。 我怎么做?
您應該取消訂閱不再需要的訂閱,方法是調用Subscription#unsubscribe
(要求您保存Subscriptions
)或通過使用Subject#complete
結束事件 stream 來完成所有訂閱 - 但這並不總是適用。
不這樣做可能會導致資源泄漏。 (這取決於實際可觀察的以及它是否作為某個點關閉)
此外,我通常也會在 ngOnDestroy 生命周期掛鈎中取消訂閱/完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.