2016-06-14 64 views
3

我有一个JSON对象是这样的:angularjs:推不是一个函数

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 functionlikedPost.likers.push(userObject);

而且userObjectvm.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"} 

任何人都可以帮我找出这个问题的原因吗?

UPDATE:

{ 
    "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);

+1

在推送电话之前,您可以添加以下内容: console.log(likedPost); 并发送结果 – Silvinus

+0

好的。给我一点时间。 @Silvinus – Annabelle

+1

这个错误意味着''likers'不是一个数组 –

回答

6

输出明确规定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); 
0

您的likedPost对象没有您期望的likers数组。在尝试推动之前,你可能会看到这是否存在。

if (typeof likedPost !== 'undefined') 
    likedPost.likers.push(userObject);