angular - 訂閱 ngrx store 會觸發多次
我有一個已設置 ngrx store 的應用。我正在訂閱它以在按鈕點擊時的函數中從 store 獲取數據,我得到了我想要的數據,但每次觸發該函數時,它似乎返回多個數據副本,並且當我再次觸發它時,數據呈指數增長。
所以在我的 component.ts 中,我有我的 selector,它連接到 store 以抓取我的資料:
this.data$ = this.store.pipe(select(selectors.dataSelector));然後我在點擊時觸發的函數(在我的 HTML 中)
onClick() {
this.data$.subscribe(x =>
console.log(x)
);
}
所以在一次迭代之後:
兩點之後:
三點過後:
諸如此類。為什麼會發生這種情況,或者有沒有不同的方法可以在 component.ts 中從商店獲取數據?我需要它只返回一次數據,否則效能將大幅下降。
答案#1
因為你每次點擊時都在訂閱 data$。如果你想在 onClick 上這麼做,可能在 console.log(x) 後取消訂閱,或者使用 rxjs take():
onClick() {
this.data$.pipe(take(1)).subscribe(x =>
console.log(x)
);
}
摘自文件:
為什麼使用 take
當你只對前面設定數量的發射感興趣時,你會想使用 take。也許你想看看使用者在第一次進入頁面時點擊了什麼,你會想要訂閱點擊事件,並只取第一次發射。
https://www.learnrxjs.io/operators/filtering/take.html
但我的建議是你在其他地方訂閱這個商店,比如在你的組件構造函數中:
constructor(store) {
store.pipe(select(selectors.dataSelector)).subscribe(x => {
this.componentX = x;
});
}
然後只要點擊,你就可以看到像這樣的資料:
onClick() {
console.log(this.componentX);
}
這樣,當元件初始化時,你只需訂閱一次。
關於訂閱和如何防止記憶體洩漏的另一件事是,當元件被銷毀時,務必要取消訂閱。
https://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables/


