无法在AngularJS中读取未定义的属性“推送”

时间:2015-12-30 01:53:39

标签: angularjs

我有一个调用4个json文件的工厂,然后我想为这些文件中的每个数据做一些处理,并将它们推送到一个对象数组中,这就是我写的代码:

2

此代码不起作用,它向我显示错误myapp.factory('wordsCloudFactory', function($http) { var factory = { getList: function() { return $http.get('data/periode_1_file.JSON') .then(function(response1) { return $http.get('data/periode_2_file.JSON') .then(function(response2) { return $http.get('data/periode_3_file.JSON') .then(function(response3) { return $http.get('data/periode_4_file.JSON') .then(function(response4) { var words = [{ 'period1': [], 'period2': [], 'period3': [], 'period4': [] }]; console.log(words); for (var i = response1.data['X_id'].length - 1; i >= 0; i--) { words['period1'].push({ id: response.data['X_id'][i], count: response.data['count'][i] }); }; for (var i = response2.data['X_id'].length - 1; i >= 0; i--) { words['period2'].push({ id: response.data['X_id'][i], count: response.data['count'][i] }); }; for (var i = response3.data['X_id'].length - 1; i >= 0; i--) { words['period3'].push({ id: response.data['X_id'][i], count: response.data['count'][i] }); }; for (var i = response4.data['X_id'].length - 1; i >= 0; i--) { words['period4'].push({ id: response.data['X_id'][i], count: response.data['count'][i] }); }; return words; }, function(error) { return 'There was an error getting data'; }) }, function(error) { return 'There was an error getting data'; }) }, function(error) { return 'There was an error getting data'; }) }, function(error) { return 'There was an error getting data'; }) } }; return factory; })

我该如何解决这个问题?

正如你在我的代码中看到的那样,有很多嵌套的message : 'Cannot read property 'push' of undefined'方法没有其他方法可以写出来吗?

1 个答案:

答案 0 :(得分:2)

您的words是一个对象数组

var words = [{
    'period1': [],
    'period2': [],
    'period3': [],
    'period4': []
}];

您必须通过索引访问它。

试试这个

words[0]['period1'].push({
    id: response.data['X_id'][i],
    count: response.data['count'][i]
});

JSFIDDLE

如果它只是一个像

的对象
var words = {
    'period1': [],
    'period2': [],
    'period3': [],
    'period4': []
};

然后你的推动没问题。

words['period1'].push({
    id: response.data['X_id'][i],
    count: response.data['count'][i]
});

JSFIDDLE