2015-05-04 27 views
2

我想要做的是取消請求或停止偵聽特定請求的響應。我不能在請求中使用timeout。是否取消的決定僅在請求完成後完成。我已經在ajax jQuery as found in this中看到了解決方案。是否有相同的角度解決方案。我使用$http來發出POST請求。AngularJS:如何終止一個http請求,我還沒有收到迴應

+0

您是否嘗試過使用請求攔截器? https://docs.angularjs.org/api/ng/service/$http – svarog

回答

4

這在the documentation描述:

超時 - {號|服務承諾} - 超時以毫秒爲單位,或已解決時,應中止請求承諾。

所以,發送請求時,通過一個承諾的配置超時,並解決它,當你決定中止:

var cancelDefer = $q.defer(); 
$http.get(url, { 
    timeout: cancelDefer.promise 
}).success(...); 

// later, to cancel the request: 
cancelDefer.resolve("cancelled"); 
+0

我可以知道哪個角度版本在超時時支持承諾對象嗎?我使用v1.2.26 –

+1

當然:轉到文檔頁面,確保選擇左上角的版本1.2.26,並查看該版本是否支持該版本。 –

0

我想補充我最近使用的的CoffeeScript版本:

canceller = $q.defer() 

$http.get (requestUrl, { timeout: canceller.promise }) 
    .then (response) -> 
    $scope.remoteData = response.data; 

$scope.cancel =() -> 
    canceller.resolve 'Cancelled http request' 
相關問題