2017-05-30 75 views
0

我有一个小问题,我想返回一个数组与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 
     } 

感谢

编辑 使用的承诺,但只返回一个数据

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 
     } 
+0

vm.getCurrentExchangeFor在$ http.get()中被异步填充。在你的http调用成功之前,你正在返回数据。使用promise来修复这个问题 – NKDev

+0

你得到空数组是因为'$ http.get'是异步的,因此在填充之前数据会被返回,但是.. $ http.get()'可能会调用它,它会严重影响性能,理想情况下,它应该在'backend side'完成,或者使用'$ q.all()'。如果仍然想这样做,那么[看到这个答案](https://stackoverflow.com/questions/25301382/javascript-getting-the-return-data-of-a-async-function-inside-a功能) – anoop

回答

1

您需要通过使用承诺这里你返回的数组是空的,因为数组在被填充之前被返回。 由于你有一个for循环和http调用,你已经使用promise.all函数来确保在返回数组之前已经填充了所有的数据。

+0

我不知道这一刻的承诺。我用小教程进行测试,它工作一半。该函数只返回一个数据。 – simonmnt

+0

这是因为它能够在到达返回语句 –

+0

'getCurrentExchangeService.getCurrentExchangeTo(2015,2,'USD')。then(function(data){console.log(data) }}时处理一个数据。 ;' 我使用这个rescup数据,但它返回一个随机数组长度 – simonmnt