Reputation: 43
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
Upvotes: 4
Views: 1909
Reputation: 37701
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
Upvotes: 2