我需要在页面加载时加载一些数据然后执行任务。为了获得我想要的数据,我执行多个不同的ajax调用。但是为了执行任务,我需要所有人确保所有的ajax调用都已完成。以下是我到目前为止所做的事情:
$q.when(
$http.get('url1').success(function (data) {
$scope.data1 = data;
console.log("ajax1 finished");
}),
$http.get('url2').success(function (data) {
$scope.data2 = data;
console.log("ajax2 finished");
}),
$http.get('url3').success(function (data) {
$scope.data3 = data;
console.log("ajax3 finished");
}),
$http.get('url4').success(function (data) {
$scope.data4 = data;
console.log("ajax4 finished");
})
).then(
console.log("All ajax calls have finished!"),
executeTask()
);
我的问题是,在所有 ajax调用完成后,块then(...);
中的代码未执行。我在我的控制台中得到了类似的内容:
ajax2 finished
ajax1 finished
All ajax calls have finished!
ajax3 finished
ajax4 finished
我一定是做错了。我怎样才能让它按照我想要的方式工作?
编辑:我尝试了以下内容,就像答案中提到的一样,但我仍面临同样的问题。
$q.all([
$http.get('url1').then(function (data) {
$scope.data1 = data;
console.log("");
}),
$http.get('url2').success(function (data) {
$scope.data2 = then;
console.log("ajax2 finished");
}),
$http.get('url3').then(function (data) {
$scope.data3 = data;
console.log("ajax3 finished");
}),
$http.get('url4').then(function (data) {
$scope.data4 = data;
console.log("ajax4 finished");
})
]).then(
console.log(""),
executeTask()
);
答案 0 :(得分:14)
我使用$q.all()
http://plnkr.co/edit/JHd3XPTKBxx4KRso5JRB?p=preview
$q.all([
$http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) {
$scope.ip.one = response.data
console.log('one')
}),
$http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) {
$scope.ip.two = response.data
console.log('two')
}),
$http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) {
$scope.ip.three = response.data
console.log('three')
}),
$http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) {
$scope.ip.four = response.data
console.log('four')
}),
]).then(function() {
console.log('all')
})
答案 1 :(得分:2)
您有两种解决方案:
您希望使用$q.all()
等待多个承诺解决。示例:http://jsfiddle.net/ThomasBurleson/QqKuk/
使用routeProvider的resolve
机制来在渲染屏幕之前预先加载承诺:https://docs.angularjs.org/api/ngRoute/provider/$routeProvider