我有一个小问题,我想返回一个带有 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
}
最佳答案
您需要在此处使用 Promise,您返回的数组为空,因为数组是在填充之前返回的。 由于您有一个 for 循环和 http 调用,因此您必须使用 Promise.all 功能来确保在返回数组之前填充所有数据。
关于javascript - 获取范围之外的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44261634/