Ant*_*Max 3 twitter-bootstrap angularjs
我正在尝试使用foreach中的顺序http请求更新进度条,这样可行,但是完全没有同步,进度条正在被http调用同步,我做错了什么?
angular.forEach(queue, function (item) {
if (item.uid) {
d.item = item;
$http({
url: BASE_URL + 'upp',
method: 'post',
data: d
}).then(function(res){
x++;
update_progress((x/queue_count)*100);
});
}
});
Run Code Online (Sandbox Code Playgroud)
我想在http返回完成时调用update_progress函数(200 OK),因此进度条正确显示实际进度.谢谢!
编辑:
我在调用*update_progress*函数之前尝试检查响应状态,但仍然无法按预期工作.我不知道在请求完成之前已经发送了200个:| 通过逻辑,res obj不应该是http请求的响应?我的意思是,如果它是200而不是错误代码,那不应该意味着请求已经完成了吗?
angular.forEach(queue, function (item) {
if (item.uid) {
d.item = item;
$http({
url: BASE_URL + 'upp',
method: 'post',
data: d
}).then(function(res){
if(res.status == 200) {
x++;
update_progress((x/queue_count)*100);
}
});
}
Run Code Online (Sandbox Code Playgroud)
阅读更多承诺atm,看看我是否可以按照@josh-strange的说法使其工作
编辑2:
所以承诺是这样做的方式,所有请求都是按顺序发送的,因此进度条按预期工作,这里是代码:
var promise = $q.all({});
// Had to init $q.all with an empty obj, 'cause null was trowing errors
angular.forEach(queue, function(item){
if (item.uid) {
promise = promise.then(function(){
d.item = item;
return $http({
url: BASE_URL + 'upp',
method: 'post',
data: d
}).then(function(res){
x++;
update_progress((x/queue_count)*100);
});
});
}
});
promise.then(function(){
end_js_update();
});
Run Code Online (Sandbox Code Playgroud)
谢谢@josh-strange
Jos*_*nge 13
Here is a working Plunker of a working example of sequential http requests. You could obviously package this up very nicely in a service but for your purposes I just put a simple example of it in a controller.
Here is the "meat" of the code:
var app = angular.module('testApp',[]);
app.controller('myController', function($scope, $http, $q){
$scope.responses = [];
$scope.doneLoading = false;
var urls = [
'http://httpbin.org/ip',
'http://httpbin.org/user-agent',
'http://httpbin.org/headers'
];
var promise = $q.all(null);
angular.forEach(urls, function(url){
promise = promise.then(function(){
return $http({
method: 'GET',
url:url
}).then(function(res){
$scope.responses.push(res.data);
});
});
});
promise.then(function(){
//This is run after all of your HTTP requests are done
$scope.doneLoading = true;
})
});
Run Code Online (Sandbox Code Playgroud)
EDIT: As Mike P says below: This is an example of chaining promises see $q documentation.
| 归档时间: |
|
| 查看次数: |
6030 次 |
| 最近记录: |