由於@asgoth返回的對象元素,我可以使用AngularJS $ HTTP服務檢索股票價格從雅虎:Cannot read response from AngularJS $resource JSONP get from Yahoo Finance無法訪問由JavaScript函數在AngularJS
在「getHistoricalPrice」功能,它將價格放在一個數組內,這個數組位於一個對象內部。從該功能內部,我可以訪問價格並將其寫入控制檯。
函數將對象返回到從中調用它。從那裏,我可以成功將整個對象寫入控制檯。但是,我無法訪問此對象的元素。我嘗試了許多不同的方式,但仍然無法訪問對象中的數據。您可以在http://jsfiddle.net/curt00/LTazR/2/或見下面的代碼:
angular.module('app', ['ngResource']);
function AppCtrl($scope, $http, $resource) {
var historical_price = getHistoricalPrice("AAPL", 'start date is hard coded', 'end date is hard coded');
console.log("after calling historical price: ", historical_price); // historical_price is an object and all of the correct data is outputted to console here, but I cannot access its elements directly from Javascript.
for(var key in historical_price) {
console.log("key =",key); // this outputs "key = list"
}
console.log("after calling getHistoricalPrice: ", historical_price.list[0][1]); // Cannot access this as browser console gives error: TypeError: Cannot read property '1' of undefined
console.log("after calling getHistoricalPrice: ", historical_price['list'][0][1]); // Cannot access this as browser console gives error: TypeError: Cannot read property '1' of undefined
console.log("after calling getHistoricalPrice: ", historical_price[0][1]); // Cannot access this as browser console gives error: TypeError: Cannot read property '1' of undefined
function getHistoricalPrice(symbol, start, end) {
var query = 'select * from csv where url=\'http://ichart.yahoo.com/table.csv?s=' + symbol + '&a=' + '11' + '&b=' + '19' + '&c=' + '2012' + '&d=' + '11' + '&e=' + '19' + '&f=' + '2012' + '&g=d&ignore=.csv\'';
var url = 'http://query.yahooapis.com/v1/public/yql?q=' + fixedEncodeURIComponent(query) + '&format=json&callback=JSON_CALLBACK';
var histData = {};
$http.jsonp(url, {timeout: 30000}).success(function(json) {
var list = [];
var result = json.query.results.row;
result.shift(); // remove the header (columns) row
angular.forEach(result, function(row) {
list.push([(new Date(row.col0)).getTime()/1000, parseFloat(row.col4)]);
});
list.sort(function(val1, val2) {
return val1[0] - val2[0];
});
histData.list = list;
console.log('Loaded historical data',histData.list[0][1],', for ' + symbol); // This works and gives the price
});
return histData;
}
var fixedEncodeURIComponent = function(str) {
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
};
}
任何幫助或建議,以解決這一問題是非常感謝!
在定義之前使用getHistoricalPrice()。 –
@DarinKolev感謝您的建議。從我調用函數的位置,我可以成功將整個對象寫入控制檯,並且可以在控制檯中查看對象陣列中的所有正確數據和數據。但是,我無法直接通過Javascript訪問元素。 – Curt