为什么 setTimeout 会阻止递归 $http.get 调用
Why is setTimeout preventing recursive $http.get call
我已经在SO上查看了它,并在谷歌上搜索了它,但我正在努力找到任何解决方案。
我有以下函数,当我不使用 setTimeout()
函数而只是调用我的轮询函数时,它会按预期工作。但是当我尝试将我的轮询函数包装在setTimeout()
中时,它工作一次,然后除非刷新页面,否则不会再次调用,我已经在 GET 请求中包含时间戳以防止使用缓存响应,所以我认为这不是问题所在。我也检查过,这种行为发生在IE9,Firefox和Chrome中。
$scope.progressPolling = function () {
var time = new Date().toString();
console.log("time :" + time);
$http.get('pollprogress?time=' + time + '&id=' + $scope.jobID)
.success(function (data, status, headers, config) {
var percent = data.percentage;
if (parseInt($scope.progress) < 100) {
if (percent <= 100) {
$scope.progress = percent;
}
setTimeout(function() {
if (parseInt($scope.progress) < 100) {
temp = parseInt($scope.progress) + 1;
$scope.progressPolling();
};
}, 5000);
}
})
.error(function (data, status, headers, config) {
console.log("Error updating Progress: " + data);
});
}
尝试将其更改为$timeout
$scope.progressPolling = function () {
var time = new Date().toString();
console.log("time :" + time);
var stop;
$http.get('pollprogress?time=' + time + '&id=' + $scope.jobID)
.success(function (data, status, headers, config) {
var percent = data.percentage;
if (parseInt($scope.progress) < 100) {
if (percent <= 100) {
$scope.progress = percent;
}
stop = $timeout(function() {
if (parseInt($scope.progress) < 100) {
temp = parseInt($scope.progress) + 1;
$scope.progressPolling();
}
else{
$timeout.cancel(stop);
}
}, 5000);
}
})
.error(function (data, status, headers, config) {
console.log("Error updating Progress: " + data);
});
}
作为旁注,创建工厂:
myModule.factory('delay', ['$q', '$timeout', function ($q, $timeout) {
return {
start: function () {
var deferred = $q.defer();
$timeout(deferred.resolve, 5000);
return deferred.promise;
}
};
}]);
之后你可以像这样调用它:
$q.all([delay.start(), /*your method */]);`
setTimeout
似乎不起作用的原因是回调函数在摘要周期之外执行,因此绑定不会更新。$timeout
服务使用 $scope.$apply(...)
包装调用,以便更新 UI。 您可以在setTimeout
回调中自己完成。
相关文章:
- 如何将PHP get查询转换为Meteor's HTTP.get()
- Angularjs http.get() Cross-Origin 请求被阻止
- Angular js http get返回所有页面
- Angular.js-$http.get-使用文件中的缓存
- 当我在chrome中切换设备模式时,$http.get请求失败
- Angular http.get没有'我不喜欢在开头和结尾加方括号的文本文件
- 从javaspring方法管理http.get响应
- 我可以在React应用程序中使用什么作为Angular的等价物;s$http.get
- 如何让foreach循环等待$http.get完成后再继续
- Angular Cross Origin Request CORS失败,但节点http.get()成功返回
- 使用$http.get()-OAuth身份验证下载带有Angular的远程文件
- $http GET URL更改并查找错误的资源
- angularJS $http.get communicating with API
- 在AngularJS中使用$http.get检索JSON时出现错误400
- AngularJS $http GET 请求到本地 JSON 文件返回语法错误:意外令牌]
- 使用角度$http.get从服务器下载文件
- AngularJS或JQuery解析错误格式的JSON(http get)
- AngularJS HTTP Get 没有得到响应
- 无法在角度 js 中将参数传递给 http get 请求
- Meteor:使用HTTP.get从客户端访问网站(CORS错误)