2017-02-17 86 views
0

我需要我的循环帮助。 我尝试从Google Finance API获取数据。 谷歌不提供multi-tiker API,因此每1个ticker提供1个请求。 对于1 ticker,它工作得很好,但我需要不止一个。 我尝试做一个循环,但我得到角度环路

未定义[对象的对象] [对象的对象]在角

.controller('currency', function ($scope, $http){ 
    var tickers =["EURUSD","AUDUSD]; 
    for (i = 0; i < 2; i++) { 
    $http.get('https://www.google.com/finance/info?q=CURRENCY%3a'+tickers[i]).then(function successCallback(response) { 
       $scope.currencydata = $scope.currencydata + JSON.parse(response.data.substr(3)); 


     })} 
    }) 
+0

'$ http.get'是异步 – Satpal

+0

使用$ q.all,对于所有的承诺 –

+1

我认为在 'VAR行情=“EURUSD”,“澳元兑美元缺少一个右引号“];' – Ernis

回答

1

JSON.parse方法输出一个对象。您无法对两个对象执行加号操作。

更改如下:

$scope.currencydata = $scope.currencydata + JSON.parse(response.data.substr(3)); 

要这样:

$scope.currencydata.push(JSON.parse(response.data.substr(3))); 

确保循环之前初始化$ scope.currencydata变量。

$scope.currencydata = []; 

否则.push方法将不可用。

+0

Thx!现在工作得很好! – user2104618

+0

没问题。很高兴你做到了! –

0

使用$ q.all做一些事情像

var functionsToFire = [] 
["EURUSD","AUDUSD].forEach(function(currncy){ 
    var hello = create http request function 
    functionsToFire.push(hello) 
}) 

$q.all(functionsToFire).then(function (result) { 
console.log(result) 
}); 

最终也应该像这样

$q.all([request1function, request2function, request3function, request4function]).then(function(result){ 
    for (var i = 0; i < result.length; i++){ 
     theResults.push(result[i]); 
    } 
}); 
0

您忘记了"。试试这个:

.controller('currency', function ($scope, $http){ 
     var tickers =["EURUSD","AUDUSD"]; 
     for (i = 0; i < 2; i++) { 
     $http.get('https://www.google.com/finance/info?q=CURRENCY%3a'+tickers[i]).then(function successCallback(response) { 
        $scope.currencydata = $scope.currencydata + JSON.parse(response.data.substr(3)); 


      })} 
     }) 
+0

yea loss“复制时 – user2104618