AngularJS:Push不是一个函数。

3

我有一个像这样的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错误,说在第likedPost.likers.push(userObject);行中,push不是一个函数

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"}

你能帮我找出这个问题的原因吗?

更新:

{
    "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
在 push 调用之前,您可以添加以下代码: console.log(likedPost); 并发送结果。 - Silvinus
好的,请稍等一下。 @Silvinus - version 2
1
这个错误意味着 likers 不是一个数组。 - Charlie
你的JSON对象来源是什么?或许在构建它或接收它时出现了错误。 - Hopeful Llama
2个回答

7
输出明确指出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);

你可以简单地写成(if likedPost),因为如果为空或未定义,它会返回false。 - MattE
1
所有理由都指向IE必须快速而又痛苦地死去。 - MattE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接