我是角度新手,一直在努力解决我的问题。
我需要多次访问 API 来获取用户数据,将所有内容存储为 JSON 数组,当收集所有数据(所有结果作为一个数组)时,需要将其传递给指令,该指令将使用它来绘制可视化(例如 d3.js) -饼形图)。
$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
});
}
}
然后将其传递给指令
<bar-chart data='allData'></bar-chart>
即使我在指令中设置 watch 并将范围设置为“=”,指令也会得到空数组。
在我的其他代码中,当我只对 json 数组执行一个 http get 调用时,我可以轻松地将其传递给指令,并且工作正常。
EDIT1:
好的,所以我现在使用前提,但 allData 数组仍然是 0。
即使有这样简单的例子:
$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
这是一个释放力量的好地方$q https://docs.angularjs.org/api/ng/service/%24q。您可以等待所有承诺解决,然后使用$q.all
方法。它只是简单地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 http://plnkr.co/edit/TF2pAnIkWquX1Y4aHExG?p=preview
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)