向mongodb提交数据时出现Angular Unshift错误

时间:2017-11-01 12:21:28

标签: javascript angularjs angular mean-stack

当我向MongoDB提交数据时,angular unshift关键字会出现此错误。我对Angular了解不多。为什么它会给我这个错误?

TypeError: Cannot read property 'unshift' of undefined

这是我的代码,它给出了这个错误:

var app=angular.module('app',[]);
app.controller('PostsCtrl', function($scope, $http){
    $http.get('/api/posts')
    .then(function(response) {
        $scope.posts = response.post;

        alert(JSON.stringify(response));
    });



$scope.addPost=function(){
    if($scope.postBody){
    $http.post('/api/posts',{
        username:'Tahir',
        body:$scope.postBody
    }).then(function successCallback(response) {
           $scope.posts.unshift(post)
           $scope.postBody=null

           alert(JSON.stringify(response));
          }, function errorCallback(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        })


        }
    }

}   

2 个答案:

答案 0 :(得分:0)

$scope.posts未定义。 你可以像这样解决它

$scope.posts = $scope.posts || [];
$scope.posts.unshift(post);

如果posts为空

,第一行检查分配空数组

答案 1 :(得分:0)

由于$scope.posts.unshift(post)$scope.posts,因此此代码undefined出现此错误,因此您应首先定义$scope.posts

可以尝试这个

var app=angular.module('app',[]);
app.controller('PostsCtrl', function($scope, $http){
    $scope.posts = [];
    $http.get('/api/posts')
    .then(function(response) {
        // if response.post is single post then should push on posts
        // $scope.posts.push(response.post);
        // if got array then 
        $scope.posts = response.post ? response.post : [];

        alert(JSON.stringify(response));
    });



$scope.addPost=function(){
    if($scope.postBody){
    $http.post('/api/posts',{
        username:'Tahir',
        body:$scope.postBody
    }).then(function successCallback(response) {
           $scope.posts.unshift(post)
           $scope.postBody=null
          }, function errorCallback(response) {
        })
        }
    }
}