2016-06-14 24 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); 
相關問題