Angular 向 mongodb 提交数据时发生 Unshift 错误

Angular Unshift error when submit data to mongodb

当我向 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.
        })


        }
    }

}   

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

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

如果 posts 为 null

,第一行检查分配空数组

由于 $scope.postsundefined,因此您应该先定义此代码 $scope.posts.unshift(post),因此您应该先定义 $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) {
        })
        }
    }
}