У меня есть массив таких объектов:
var myArray = [{post:{message:"hi",user:"joe"}},{post:{message:"how are you",user:"bob"}}];
где myArray[0].post.user = "joe"
и myArray[1].post.user = "bob"
Я хочу добавить еще один ключ (т. comment
) для динамической post
на основе асинхронного вызова с использованием $ resource при циклическом перемещении по массиву.
Служба удаленных 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
?
Я полагаю, что ваша проблема связана с переменной C: возможно, ваша переменная C (которая используется совместно с вашим циклом for) переходит в "onward", когда вызывается функция "then".
комментарий моего комментария, который служил ответом
comments
от обещания, что он отображает?Resource { id:"1",comment:"This is my comment" }