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