2014-09-20 2 views
0

내 컨트롤러에서 getStuff 함수를 호출하려고하는데 "정의되지 않은 함수입니다"라는 오류가 콘솔에 표시됩니다. GET에서 JSON을 반환하고 $ scope 변수에 저장하려고합니다.팩토리 함수에 액세스 할 수 없음 (정의되지 않음이 함수가 아닙니다)

app.factory('UserInfo', function($http) { 

var user = []; 

return{ 
     getStuff: function(){ 
      user.push($http.get('api/users')); 
      return user; 
    }, 
     testPost: function(){ 
      return $http.post('api/users'); 
    } 
}; 

}); 나는 공장 기능을

$scope.datapls = function() { 
    UserInfo.getStuff().success(function(response){ 
     console.log(response); 
     $scope.loaduser.push(response); 
    }); 
} 

감사 전화를 사용하고

.controller('TwitterController', function($scope, $q, $interval, UserInfo) { 

다음 여기에 $ 범위 함수의로

공장은 컨트롤러에 매여있다! 도움에 감사드립니다.

답변

1

오류는 .success() 기능을 나타내며 존재하지 않습니다.

약속을 사용하려는 것 같습니다. 그렇다면 return 서비스의 약속 그 자체가 필요합니다.

이와 비슷한 것 (테스트되지는 않았지만 아이디어). 컨 터롤러가 아닌 서비스에 $q을 사용하려고합니다.

$q on AngularJS docs 섹션의 예는 훌륭합니다.

이렇게하면 컨트롤러가 데이터를 기다릴 필요가 없습니다. 즉시이

app.service('UserInfo', function($http, $q) { 
     this.getStuff = function(){ 
      var deferred = $q.defer(); 
      $http.get('api/users').success(function(data, status) { 
       deferred.resolve(data); 
      }).error(function(data, status) { 
       deferred.reject(data); 
      }); 

      return deferred.promise; 
     } 
    } 
); 

해결 그리고 컨트롤러에 당신이 할 수있는 : 자체에 docs, $ HTTP는 약속을 반환에 따르면

UserInfo.getStuff().then(function(dataFromService){ 
     // dataFromService is used in here.. 
     $scope.loaduser.push(dataFromService); 
    }, function(error) { 
    // the error will come in via here 
    }); 
+0

고맙습니다! 필자는 $ q 문서를 읽고이를 내 코드에 적용하여 효과적이었습니다. – DaveS

+0

우수 :-) 예전에 익숙해 져야하는 이상한 일이지만 약속은하지만 빌딩 블록은 :-) – Darren

0

을, 당신을 위해 귀하의 공장 기능을 변경할 수 있습니다 당신이해야 할 노력하고 무엇을 달성 :

app.factory('UserInfo', function($http) { 

return{ 
     getStuff: function(){ 
      return $http.get('api/users')); 
    }, 
     testPost: function(){ 
      return $http.post('api/users'); 
    } 
}; 
}); 

을 컨트롤러에서 :

$scope.datapls = function() { 
    UserInfo.getStuff().then(function(response){ 
     console.log(response); 
     $scope.loaduser.push(response); 
    }); 
} 
관련 문제