AngularJS - Collecting multiple get requests into json array and then passing to directive

自作多情 提交于 2019-12-23 12:13:52

问题


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

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.

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:

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");
    }
});

in html {{ allData ]] // 0


回答1:


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.

See this example:

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
         });
    }
})

See it in action here: http://plnkr.co/edit/TF2pAnIkWquX1Y4aHExG?p=preview



来源:https://stackoverflow.com/questions/27644047/angularjs-collecting-multiple-get-requests-into-json-array-and-then-passing-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!