Angularjs 以串行方式在angular中重复ajax调用并在需要时取消调用的最干净的方法?
我试图重复一个用于pulsing的ajax调用,但使用interval时,由于网络问题,有时我会有几个ajax调用在队列中。如何运行ajax调用,但只有在第一个调用成功返回时才运行下一个调用。另外,如果需要的话,我想取消这个电话。使用间隔这很容易,因为我使用clearIntervalAngularjs 以串行方式在angular中重复ajax调用并在需要时取消调用的最干净的方法?,angularjs,ajax,Angularjs,Ajax,我试图重复一个用于pulsing的ajax调用,但使用interval时,由于网络问题,有时我会有几个ajax调用在队列中。如何运行ajax调用,但只有在第一个调用成功返回时才运行下一个调用。另外,如果需要的话,我想取消这个电话。使用间隔这很容易,因为我使用clearInterval $scope.intervalLoop = $interval(function() { if ($scope.weAreClear) $scope.initSoftwareUpdate(); }, 5
$scope.intervalLoop = $interval(function() {
if ($scope.weAreClear)
$scope.initSoftwareUpdate();
}, 5000);
如前所述,您可以使用递归函数返回
$timeout
:
$scope.cancelled = false;
$scope.recTimeoutFunction = function($scope) {
return $timeout(function($scope) {
//only start new pulse if user hasn't cancelled
if(!$scope.cancelled)
{
$http(/* pulsing ajax call */)
.then(function(res) {
//after successful ajax call, start new timeout:
$scope.recTimeoutFunction($scope);
})
}
}, 5000, true, $scope);
};
//initially call the timeout function:
$scope.recTimeoutFunction($scope);
//function for the user to cancel pulsing messages
$scope.cancel = function() {
$scope.cancelled = true;
}
如前所述,您可以使用递归函数返回
$timeout
:
$scope.cancelled = false;
$scope.recTimeoutFunction = function($scope) {
return $timeout(function($scope) {
//only start new pulse if user hasn't cancelled
if(!$scope.cancelled)
{
$http(/* pulsing ajax call */)
.then(function(res) {
//after successful ajax call, start new timeout:
$scope.recTimeoutFunction($scope);
})
}
}, 5000, true, $scope);
};
//initially call the timeout function:
$scope.recTimeoutFunction($scope);
//function for the user to cancel pulsing messages
$scope.cancel = function() {
$scope.cancelled = true;
}
timeout vs intervalTimeout将只运行一次,完成后,您将启动另一个,从而使它们无法堆积。您可以使用
$scope.on('myEvent',function(){…})侦听事件编码>并从$http
承诺($scope.broadcast('myEvent');
)的resolve
函数中触发事件这不是最好的方式,但这是我能想到的最好的方式,提供了关于此问题的信息Timeout vs intervalTimeout只运行一次,完成后,您可以启动另一个,您可以使用$scope.on('myEvent',function(){…})监听事件
并从$http
promise($scope.broadcast('myEvent');
)的resolve
函数中触发事件这不是最好的方法,但这是我能想到的关于这个问题的最好方法