Angularjs Can';t访问工厂功能(未定义不是功能)

Angularjs Can';t访问工厂功能(未定义不是功能),angularjs,Angularjs,我试图从我的控制器调用getStuff函数,但是我在控制台中得到一个错误,说“undefined不是一个函数”。我试图从GET返回JSON,然后将其存储在$scope变量中 app.factory('UserInfo', function($http) { var user = []; return{ getStuff: function(){ user.push($http.get('api/users')); return

我试图从我的控制器调用getStuff函数,但是我在控制台中得到一个错误,说“undefined不是一个函数”。我试图从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');
    }
};
}))

工厂连接到控制器,如下所示

.controller('TwitterController', function($scope, $q, $interval, UserInfo) {
这是我用来调用工厂函数的$scope函数

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

谢谢!感谢您的帮助。

您的错误指的是
.success()
函数-它不存在

看起来你在试图使用承诺。如果是这种情况,那么您需要
从您的服务中返回
承诺本身

类似这样的东西(不是经过测试,而是一个想法)。您希望在您的服务中使用
$q
,而不是您的控制器

本节中的示例非常好

这样,控制器就不必等待数据了。一旦解决了

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;
        }
    }
);
在控制器中,您可以执行以下操作:

  UserInfo.getStuff().then(function(dataFromService){
       // dataFromService is used in here..
       $scope.loaduser.push(dataFromService);
    }, function(error) {
     // the error will come in via here
  });
根据$http本身返回的承诺,您可以更改factory函数以实现您尝试执行的操作:

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);
    });
}

非常感谢。我阅读了$q文档,并将其改编为我的代码,它成功了。非常好:-)这是一件奇怪的事情,承诺,但构建块:-)