2017-02-17 21 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