2014-08-31 59 views
0

假設我們有一個自動完成一個超級簡單的搜索觸發的KEYUP /擊的$ http.get()請求:確保在AngularJS後續HTTP Ajax調用的正確順序

<input type="text" ng-model="keyword" ng-change="makeRequest()"> 

$scope.makeRequest = function() { 
    $http.get(url).then(function(res) { 
     // update the typeahead list here. 
    }); 
} 

維持傳遞響應的順序的最簡單方法是什麼?由於變化的延遲,更早的結果通常會最終導致用戶混淆。 我正在尋找一些順序,而不是直接去抖,這將防止在某個按鍵間隔下發出請求。

回答

1

您可以跟蹤最新的請求和響應忽略,除非它從最新的...

var latestRequest = 0; 
$scope.makeRequest = function() { 
    var thisRequest = ++latestRequest; 
    $http.get(url).then(function(res) { 
     if (thisRequest === latestRequest) { 
     // update the typeahead 
     } 
    }); 
} 
+0

我已經想通這是最簡單和最直接的方式做到這一點有一個時間間隔組合檢查(只是爲了讓API休息一下)。最後在params中檢查最新的關鍵字,而不是查詢計數本身:'$ http.get(url,params).then(function(res.data){if(params.keyword === latestKeyword){$ scope.results = res.data});' – ienes 2014-09-01 08:30:22

相關問題