【发布时间】: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.posts是undefined,因此您必须检查$scope.posts是否为undefined,否则您应该首先定义$scope.posts = []
标签: javascript angularjs angular mean-stack