2017-06-26 39 views
0

我有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中省略先前的請求?那可能嗎?

+0

中的第三個回調函數訂閱爲[完成](http://reactivex.io/rxjs/class/es6/Subscriber.js~Subscriber.html) – Dhyey

回答

0

的幾個注意事項:

你可能想一個去抖添加到nr流。這樣,如果用戶以快速成功鍵入多個號碼,則不會爲每個號碼發送請求。 debounceTime()允許您在輸入一個值後等待一個毫秒的設定值,如果在那段時間內沒有輸入新的值,它會被傳遞。如果在設定時間內輸入新值,時間將被重置;沖洗並重復。

您不應該在subscribe()中執行異步工作,它會「破壞」Rx。所有異步工作應在subscribe()之前在另一個運營商內完成;經常是一個*Map()運營商。


我假設someMethod()返回一個可觀察到的(或者你也許可以將其轉換爲一個),在這種情況下,你會希望switchMap()操作。您返回switchMap()中的可觀察值,它只會訂閱最近的可觀察值。它也將退訂先前的觀察。

let stream, 
nr = document.querySelector('input').value 
    .debounceTime(500); // This will wait 500 ms before passing on a value 
         // If a new value arrives before 500ms has passed, it resets the time 

stream = nr 
    .switchMap(num => someService.someMethod(num)) 
    .subscribe(clonedNr => console.log(`received response for ${clonedNr}`)); 
相關問題