2 回答

TA貢獻1776條經驗 獲得超12個贊
Nilesh Patel 提供的答案應該可以正常工作,但我仍然想添加這個答案來分享一些您可能需要在應用程序中使用的小技巧和改進。
請看一下這個Stackblitz 演示。
首先要注意的是,如果您正在使用該timer
運算符并且您有興趣在它第一次發出時執行某些操作,您可以檢查該運算符返回的值并查看它是否為0
:
我試圖每 10 秒調用一次服務,但也想僅在第一次發射時執行一些代碼,這里的問題是第一個條目是重復的,代碼如下:
ionViewWillEnter() {
this.isLoading = true;
const Obs = timer(0, 10000).pipe(
switchMap(() => {
return this.serviceName.someFunc();
})
);
this.timerSub = Obs.subscribe();
this.timerSub = Obs.pipe(first()).subscribe(() => {
this.isLoading = false;
});
}
我還注意到另一個問題,即即使我在離開頁面時取消訂閱,該服務仍然每 10 秒調用一次,任何幫助都會受到贊賞。
更新
我找到了一個解決方案,但它更多的是一種解決方法,基本上我所做的是在訂閱上設置 setTimeout :
this.timerSub = Obs.pipe(first()).subscribe(() => {
this.isLoading = false;
});
setTimeout(() => {
this.timerSub = Obs.subscribe();
}, 10000);
顯然,取消訂閱問題也得到了解決,盡管我希望得到一些更優雅的解決方案的反饋,提前致謝。

TA貢獻1793條經驗 獲得超6個贊
更好的解決方案:
在頂部創建變量firstSub 。
ionViewWillEnter() {
this.isLoading = true;
this.timerSub = timer(0, 10000).pipe(
switchMap(() => {
return this.serviceName.someFunc();
})
);
this.firstSub = this.timerSub.pipe(first());
this.firstSub.subscribe(() => {
// only emit once(first)
this.isLoading = false;
});
}
在組件視圖銷毀之前取消訂閱。
ngOnDestroy(){
this.timerSub.unsubscribe();
this.firstSub.unsubscribe();
}
添加回答
舉報