【问题标题】:Cannot access elements in object returned by Javascript Function in AngularJS无法访问 AngularJS 中的 Javascript 函数返回的对象中的元素
【发布时间】:2012-12-08 09:29:20
【问题描述】:

感谢@asgoth,我可以使用 AngularJS $http 服务从 Yahoo 检索股票价格,如下所述:Cannot read response from AngularJS $resource JSONP get from Yahoo Finance

在“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 直接访问元素。

标签: javascript arrays function object angularjs


【解决方案1】:

这是时间问题。

在第 12-14 行中,您尝试在填充 histData.list 之前访问它。这是因为这段代码是在 $http.jsonp 函数的成功回调执行之前运行的。

任何依赖于该回调完成的代码都必须在回调中或在回调中调用的函数中。

【讨论】:

  • 感谢 BobS 的建议。从调用函数的位置,我可以成功地将整个对象写入控制台,并且可以在控制台中看到所有对象的数组和数据。这不意味着它被填充了吗?但是,我无法访问该对象的元素。不过,我会尝试你的建议。
  • 我尝试将回调函数放入我的本地文件中。回调没有被执行。您可以在我更新的 jsFiddle 中了解我所做的事情:jsfiddle.net/curt00/LTazR/7 我欢迎任何其他建议。
  • 我得到了回调工作,但我的情况与以前完全相同。当我将对象写入控制台时,所有内容(数组)都是正确的,但我无法使用调用函数的 Javascript 访问数组。
【解决方案2】:

https://stackoverflow.com/a/13967709/1916258上查看我的回答

调试 Yahoo api 的一个好方法是使用 YQL 控制台:http://developer.yahoo.com/yql/console/

有关不同可能性的信息(哪些股票信息)可以在http://www.gummy-stuff.org/Yahoo-data.htm找到

编辑:函数 fixedEncodeURIComponent 仍然存在问题。它也应该对引号 (") 进行编码:

var fixedEncodeURIComponent = function(str) {
    return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A").replace(/\"/g, "%22");
};

【讨论】:

    【解决方案3】:

    BobS 是对的,你没有正确计时。在调用它之后,您还声明了 fixedEncodeURIComponent。这导致我在加载 jsfiddle 时立即出现错误。

    当您正确地将回调传递给您的函数时,您实际上并没有调用它。我删除了 json 的所有后处理,因为您还有一些涉及查询的其他错误,只是实现了回调,以便您可以看到它正在工作。

    请求完成后仍处于success函数需要添加

    if(typeof(callback) === "function"){
        callback();
    }
    

    这会调用你传入的函数并运行它。这是一个有效的jsFiddle: http://jsfiddle.net/LTazR/22/

    我还更新了我创建的调用输出的一个新变量,以便您可以看到它的变化。

    【讨论】:

      【解决方案4】:

      感谢大家提供建议。

      我通过使用 AngularJS 的 $scope 变量解决了这个问题,例如 $scope.symbol[user].price。我在调用 getHistoricalPrice 函数之前创建了这个变量,然后在该函数中,从 $http.jsonp 返回结果后,我将值放入 $scope 变量中,如下所示:

      $scope.symbol[user].price = row.col4;
      

      【讨论】:

        猜你喜欢
        • 2020-08-12
        • 2012-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 2013-10-10
        • 2020-01-31
        相关资源
        最近更新 更多