【发布时间】:2017-05-30 11:57:17
【问题描述】:
我有一个小问题,我想在 Angular 中返回一个带有函数的数组。 我在一个匿名函数中处理我的数据,当我返回数组时它是空的。
我不知道该怎么办...
getCurrentExchangeTo : function(year, month, country){
var numberDayPerMonth = [
31,
28,
31,
30,
31,
30,
31,
30,
31,
30,
31,
30,
];
var vm = this;
this.country = country;
this.getCurrentExchangeFor = [];
var hello = "gello"
for(var i = 0; i < numberDayPerMonth.length; i++){
if((i + 1) === month){
for(let j = 1; j < numberDayPerMonth[i]; j++){
$http.get('http://api.fixer.io/' + year + '-0' + month + '-0' + j +'?symbols=' + vm.country).then(function (success) {
let countryDay = vm.country
vm.getCurrentExchangeFor[j] = success.data.rates[countryDay];
});
}
}
}
return vm.getCurrentExchangeFor
}
谢谢
编辑 使用 promise 但它只返回一个数据
getCurrentExchangeTo : function(year, month, country){
var def = $q.defer();
var numberDayPerMonth = [
31,
28,
31,
30,
31,
30,
31,
30,
31,
30,
31,
30,
];
var vm = this;
this.country = country;
this.getCurrentExchangeFor = [];
var hello = "gello"
for(var i = 0; i < numberDayPerMonth.length; i++){
if((i + 1) === month){
for(let j = 1; j < numberDayPerMonth[i]; j++){
$http.get('http://api.fixer.io/' + year + '-0' + month + '-0' + j +'?symbols=' + vm.country).then(function (success) {
let countryDay = vm.country
vm.getCurrentExchangeFor[j] = success.data.rates[countryDay];
def.resolve(success.data.rates[countryDay])
});
}
}
}
return def.promise
}
【问题讨论】:
-
vm.getCurrentExchangeFor 被填充到异步的 $http.get() 中。在您的 http 调用成功之前,您正在返回数据。使用 promise 来解决这个问题
-
你得到空数组,因为
$http.get是异步的,因此数据在填充之前返回,但是.. 所以$http.get()调用?,它只会严重影响性能,理想情况下,应该这样做在backend side.. 或使用$q.all()。如果仍然想这样做,那么see this answer
标签: javascript angularjs arrays scope