【问题标题】:Angular Unshift error when submit data to mongodb向 mongodb 提交数据时出现 Angular Unshift 错误
【发布时间】:2017-11-01 12:21:28
【问题描述】:

当我向 MongoDB 提交数据时,角度 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.unshift(post) 的此错误,因为$scope.postsundefined,因此您必须检查$scope.posts 是否为undefined,否则您应该首先定义$scope.posts = []

标签: javascript angularjs angular mean-stack


【解决方案1】:

此代码$scope.posts.unshift(post) 出现此错误,因为$scope.postsundefined,因此您应该首先定义$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) {
        })
        }
    }
}   

【讨论】:

    【解决方案2】:

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

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

    如果posts 为空,则第一行检查分配空数组

    【讨论】:

    • 感谢您的帮助,先生,您太棒了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多