AngularJS - 收集多个GET请求为JSON数组,然后传递给指令 [英] AngularJS - Collecting multiple get requests into json array and then passing to directive

查看:176
本文介绍了AngularJS - 收集多个GET请求为JSON数组,然后传递给指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我新的角度和一直在努力如何解决我的问题。

I am new to angular and been struggling how to solve my problem.

我需要访问API多次为用户的数据,存储一切,JSON数组,当收集到的所有数据(所有结果为一个数组)需要将它传递给指令,它会用它来绘制可视化(如: d3.js-饼图)。

I need to access API multiple times for users data, store everything as JSON array and when all the data is collected(all results as one array) it needs to be passed to directive which will use it to draw visualization(eg. d3.js-pie chart).

$scope.allData = [];

$http.get("****link here****/students")
    .success(function (data) {
        students = data;

        for (i = 0; i < students.length; i = i + 1) {

            $http.get("**** link here ****/quest/" + students[i].id)
                .success(function (data) {
                    quest = data;

         $scope.allData.push({
                            id: quest.id,
                            value: quest.length
                        });
           }
        }

,然后把它传递给指令,因为

and then pass it to directive as

   <bar-chart data='allData'></bar-chart>

即使我设置观看指令,并具有范围为=指令得到空数组。

even if I set watch in directive and have scope as '=' the directive gets empty array.

在我的其他code时,我只是做一HTTP GET呼吁JSON数组我可以通过它方便地指令,并能正常工作。

In my other code when I just do one http get call for json array I can pass it to directive easily and it works fine.

EDIT1:

行,所以我现在用premises,但仍ALLDATA数组是0。
即使是简单的例子是这样的:

OK so I use premises now, but still allData array is 0. Even with simple example like this:

 $scope.allData = [];
 var promieses = [];
 for (i = 0; i < 10; i = i + 1) {

            promieses.push($http.get("***link***/student/" + students[i].id));
}

$q.all(promieses).then(function (data) {
    for (i = 0; i < data.length; i = i + 1) {
        $scope.allData.push("test");
    }
});

在HTML {{ALLDATA] // 0

in html {{ allData ]] // 0

推荐答案

这是发动的 $ q 。您可以等待所有的承诺来解决,然后用 $ q.all 方法处理。它只是将多个承诺到时所有的输入承诺的决心是解决一个承诺。

This is a great place to unleash the power of $q. You can wait for all the promises to resolve and then process them using $q.all method. It simply Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

请参阅下面的例子:

students = data;
var promises = [];
for (i = 0; i < students.length; i = i + 1) {

    promises.push($http.get("**** link here ****/quest/" + students[i].id));

}

$q.all(promises).then(function(response) {
    for (var i = 0; i < response.length; i++) {
         $scope.allData.push({
             id: response[i].data.id,
             value: response[i].data.length
         });
    }
})

看到它在这里的行动: http://plnkr.co/edit/TF2pAnIkWquX1Y4aHExG p = preVIEW

这篇关于AngularJS - 收集多个GET请求为JSON数组,然后传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆