我有一个像这样的对象数组:
var myArray = [{post:{message:"hi",user:"joe"}},{post:{message:"how are you",user:"bob"}}];
其中myArray[0].post.user = "joe"
和myArray[1].post.user = "bob"
我希望在循环遍历数组的同时,使用$ resource基于异步调用动态地向comment
添加另一个键(即post
。
远程Comments
服务效果很好,如下所示:
.factory('Comments',function($resource, myUrl) {
var comments = $resource(myUrl + 'api/comments/:postId', {postId: '@id'});
return comments;
})
在我的控制器中
var myArray = [{post:{message:"hi",user:"joe"}},{post:{message:"how are you",user:"bob"}}];
var messageCount = myArray.length;
var post_id = 1; //comes from elsewhere
for (var c = 0; c < messageCount; c++) {
Comments.get({postId:post_id}).$promise.then(function(comments) {
console.log(comments); // <<---- objects appear to be fine in the console log
myArray[c].post.comments = comments; // <---- throws undefined error
});
}
为什么myArray.post.comments = comments
抛出错误Cannot set property 'user' of undefined
??
答案 0 :(得分:1)
我猜你的问题与C变量有关:也许你的C变量(在你的for循环中共享)已经过去&#34;向前&#34;当&#34;然后&#34;函数被调用。
重新发布我的评论作为答案