我有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