2016-11-03 74 views
0

我正在嘗試實現一項服務,該服務每5秒發出一次休息呼叫。之前我使用的是$ interval,但是我意識到如果由於互聯網連接問題導致請求花費的時間超過5秒,則可能會遇到麻煩。

service.fetchData= function() { 
     //UpdateHandler is my handler function which just fills my json array 
     restApiService.requestFromApi("REST" + '?latitude=' + latestCoords.latitude + '&longitude=' + latestCoords.longitude + '&radius=' + config.radiusInMetres, updateHandler); 
    }; 

    $timeout(service.fetchData, 5000); 

fetchData仍然只被調用一次。

我們如何使用超時多次調用和使用的承諾(我不是很熟悉的承諾)

回答

1

如果你要堅持$timeout,你應該遞歸調用函數,以超時,然後請求到API完成。

service.fetchData= function fetchData() { 
    //UpdateHandler is my handler function which just fills my json array 
    restApiService.requestFromApi("REST" + '?latitude=' + latestCoords.latitude + '&longitude=' + latestCoords.longitude + '&radius=' + config.radiusInMetres, updateHandler) 
    .finally(function(){ 
      $timeout(fetchData, 5000)// Call new fetchData after finish previous 
     }); 
}; 

$timeout(service.fetchData, 5000); 

angular.module('ExampleApp', []) 
 
    .controller('ExampleController', function(restApiService, $timeout) { 
 
    var vm = this; 
 
    this.fetchData = function() { 
 
     console.log("start request"); 
 
     restApiService.requestFromApi("data") 
 
     .then(function() { 
 
      console.log("success response"); 
 
     }) 
 
     .finally(function() { 
 
      console.log("request again"); 
 
      fetchByTimeout();// Call new fetchData after finish previous 
 
     }); 
 
    }; 
 

 
    function fetchByTimeout() { 
 
     $timeout(vm.fetchData, 5000); 
 
    } 
 
    fetchByTimeout(); 
 
    }) 
 
    // Service for simulate long API call 
 
    .service("restApiService", function($q, $timeout) { 
 
    return { 
 
     requestFromApi: function(request) { 
 
     var defer = $q.defer(); 
 
     //simulate 10 seconds API call 
 
     $timeout(defer.resolve, 10000); 
 
     return defer.promise; 
 
     } 
 
    } 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="ExampleApp"> 
 
    <div ng-controller="ExampleController as vm"> 
 

 
    </div> 
 
</div>

+0

終於使用時,我經常得到這個錯誤Uncaught TypeError:無法讀取屬性'finally'undefined(...) –

+0

@AbdulSalamShaikh函數'requestFromApi'需要返回一個承諾。顯示'requestFromApi'函數的代碼。 –

+0

http://stackoverflow.com/questions/40630494/cannot-read-property-finally-of-undefined-while-trying-to-make-rest-call –

0

不能使用$timeOut多個calls.As%的docs,調用$超時的返回值是一個承諾,當延遲已經過去並且超時函數(如果提供的話)被執行時將被解決。簡而言之,它將在時間延遲後執行一次

您以前使用的是$interval對於您的要求是正確的。爲了避免您提出的問題(慢速上網,並在前一個完成之前新的呼叫),使用一個標誌。

//if(flag is false) 
// set flag to true and make http call 
// upon return from call, set flag to false 

現在在您的$interval函數調用中使用此登錄。希望這可以幫助。

+0

我如何可以使用納入承諾這段代碼,如果你能扔一些輕? –

+0

承諾將從應該進行http調用的服務返回。該標誌應該在您的控制器中調用該服務。並且控制器內部的$ interval也會根據標誌條件調用服務 – sisyphus