我有Angular輸入,每當它的值發生變化時我要求服務獲取有關輸入值的一些數據。我只關心最後輸入的輸入,所以當用戶輸入'1',但是然後擦除它並輸入'2'時,我不關心關於先前值的數據。我寫了這樣的事情(我一直在prevNr先前請求的值):取消來自Observable的傳入數據
let stream,
nr = document.querySelector('input').value;
if (status === `${nr} in progress`) {
stream.unsubscribe();
console.log(`subscription of ${prevNr} cancelled`)
}
status = 'in progress';
prevNr = nr;
console.log(`started subscription of ${nr}`)
stream = someService.someMethod.subscribe(() => {
const clonedNr = nr;
setTimeout(() => {
status = 'done';
console.log(`received response for ${clonedNr}`)
}, 12000);
})
我回來在控制檯
1 in progress
subscription of 1 cancelled
2 in progress
subscription of 2 cancelled
3 in progress
subscription of 3 cancelled
4 in progress
received response for 1
received response for 2
received response for 3
received response for 4
現在我用的setTimeout()嘲笑迴應,但我可以想象我在輸入3的數據之前接收輸入4的數據的情況,並且結果這個數據將被分配給錯誤的輸入。 如何在Observable中省略先前的請求?那可能嗎?
中的第三個回調函數訂閱爲[完成](http://reactivex.io/rxjs/class/es6/Subscriber.js~Subscriber.html) – Dhyey