我有 Angular 输入,每次它的值发生变化时,我都会要求服务获取有关输入值的一些数据。我只关心上次输入的输入,所以当用户输入“1”,然后将其删除并输入“2”时,我不关心有关先前值的数据。我写了这样的东西(我在 prevNr 中保留了先前请求的值):
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 中省略以前的请求?那可能吗?