比较来自世界各地的卖家的域名和 IT 服务价格

AngularJS + $q, 完成几个后做点什么 ajax 呼叫

加载页面时,我需要下载一些数据,然后执行任务。 要获取所需的数据,我执行几个不同的呼叫。 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//
/;


我的问题在于块中的代码
then/.../;

没有被执行

完成全部后

呼叫 ajax. 我在我的控制台中得到了这样的东西:


ajax2 finished
ajax1 finished
All ajax calls have finished!
ajax3 finished
ajax4 finished


我一定做错了什么。 我怎样才能让他像我想要的那样工作?

Edit

: 我尝试了以下答案,但我仍然遇到同样的问题。


$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//
/;
已邀请:

郭文康

赞同来自:

我为你做了一个工作的planker
$q.all//


http://plnkr.co/edit/JHd3XPTKB ... eview

$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'/
}/

知食

赞同来自:

你有两个解决方案 :

你想用
$q.all//

为了等待一些承诺的解决。 例子:
http://jsfiddle.net/ThomasBurleson/QqKuk/
/

使用机制
resolve

的 routeProvider 为了在显示屏幕之前预加载承诺 :
https://docs.angularjs.org/api/ngRoute/provider/$routeProvider

要回复问题请先登录注册