我有一个像这样的JSON对象:
var post = {
"post_id": "1",
"content": "content",
"post_author": {
"id": "12",
"firstName": "Amelia",
"lastName": "Earheart",
},
"isLiked": false,
"likes_count": 0,
"likers": [],
"comments_count": 0,
"commenters": [],
"comments": []
};
并且post
从前端传递到下面给出的函数。
var vm = this;
vm.likePost = function(post) {
var likedPost = post;
vm.userInfo();
likedPost.likers.push(userObject); //Here
myService.postLike(likedPost).success(function(data) {
likedPost.isLiked = true;
likedPost.likes_count++;
vm.posts = data;
});
};
但是这样做,我得到了一个JavaScript错误,说的很push is not a function
对likedPost.likers.push(userObject);
并且userObject
由返回vm.userInfo()
,它看起来像这样:
vm.userInfo = function() {
myService.getBasicUserInfo().success(function(data) {
vm.currentPost.post_author.id = data.id;
vm.currentPost.post_author.firstName = data.firstName;
vm.currentPost.post_author.lastName = data.lastName;
});
};
返回的JSON是这样的:
{"id":"12","firstName":"Amelia","lastName":"Earheart"}
谁能帮助我找出造成此问题的原因?
更新:
{
"post_id": "12",
"content": "Content is the content that contains the content",
"image": "member-default.jpg",
"created_at": "2016-05-26 14:29:00",
"post_author": {
"id": "12",
"firstName": "Amelia",
"lastName": "Earheart",
},
"isLiked": false,
}
这就是我得到的 console.log(likedPost);
输出明确指出likers
未定义。您可以在使用push()
方法之前进行验证检查。
//if likedPost.likers is not defined, it will define it as an array
likedPost.likers = likedPost.likers || [];
//Do the push operation
likedPost.likers.push(userObject);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句