【发布时间】:2015-02-13 04:17:45
【问题描述】:
我有一项服务,它每 3 秒检查一次项目状态。如果项目状态为就绪,则返回状态字符串。否则,请使用$timeout 等待 3 秒,然后重试。
我的问题是当用户触发某些事件(例如:离开当前页面)时,我想取消或停止递归超时,但我不知道该怎么做。
服务:
angular.module('app')
.factory('ItemService', ItemService);
function ItemService($timeout, DataService) {
var service = {
checkStatus: checkStatus
};
function checkStatus() {
return DataService.getItemStatus()
.then(function(status){
if (status === 'ready') {
return status;
} else {
// the item is not ready. Check again after 3 seconds
return $timeout(function() {
return checkStatus();
}, 3000)
}
});
}
}
客户:
angular.module('app')
.controller('ItemCtrl', ItemCtrl);
function ItemCtrl($scope, ItemService) {
ItemService.checkStatus()
.then(function(status) {
// do somethin when item is ready.
});
$scope.$on('destroy', function(){
// Should stop the $timeout recursive, but don't know how..
});
}
【问题讨论】:
-
您可能会为某些事件附加一个布尔值,然后在您的状态检查中,还检查是否触发了其中一个事件
-
如果只需要检查一项,可以解决问题。如果在同一页面上要检查两个项目,而我有时只想停止其中一个项目怎么办?
-
我也有同样的问题,希望得到解答。
-
如果
getItemStatus已经返回了一个promise,为什么它会在状态真正准备好之前触发一个resolve? -
@rgthre my
getItemStatus实际上是对后端服务器的 GET 请求,它将立即返回带有字符串ready或processing的项目状态,因此只要后端返回字符串。
标签: javascript angularjs recursion