2017-11-01 6 views
-1

MongoDB에 데이터를 제출할 때 angular unshift 키워드가이 오류를 표시합니다. Angular에 대해 많이 알지 못합니다. 왜 이런 오류가 나옵니까?mongodb에 데이터를 제출할 때 각도 Unshift 오류

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

시도 할 수있는 것은''undefined'입니다 $ scope.posts'는'undefined'이거나'$ scope.posts = []'와 같이 먼저 정의해야합니다 –

답변

0

null의 경우 첫 번째 줄에 검사가 빈 배열을 할당이

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

처럼 해결할 수 있습니다. 당신이 검사해야하므로

당신 때문에 $의 scope.posts``의이 코드`$의 scope.posts.unshift (게시물)`이 오류를 가지고이 일

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) { 
     }) 
     } 
    } 
} 
+0

천재입니다 :) 해결 된 문제 –

0

$scope.posts이 정의되지 :

TypeError: Cannot read property 'unshift' of undefined 

다음은이 오류를 제공 내 코드입니다. 당신은 posts$scope.postsundefined된다 그래서 처음 $scope.posts을 정의해야합니다 $scope.posts.unshift(post) 때문에이 코드에 대해이 오류가 발생했습니다

+0

여러분의 도움에 감사드립니다 선생님 당신은 위대한 분입니다 –