DaveS
DaveS

Reputation: 99

Can't Access Factory Function (Undefined is not a function)

I'm trying to call the getStuff function from my controller, but I get an error in the console saying that "undefined is not a function". I'm trying to return JSON from the GET and then store it in a $scope variable.

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

});

The factory is hooked up to the controller as follows

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

and here's the $scope function I'm using to call the factory function

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

Thanks! I appreciate the help.

Upvotes: 0

Views: 228

Answers (2)

V31
V31

Reputation: 7666

According to the docs, $http in itself returns a promise, you can change your factory function in order to achieve what you trying to do:

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

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

and in the controller:

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

Upvotes: 0

Darren Wainwright
Darren Wainwright

Reputation: 30727

You're error refers to the .success() function - it doesn't exist.

It looks like you're trying to use promises. If that's the case, then you need to return the promise itself from your service.

Something like this (not tested, but an idea). You want to use the $q in your service, not your contorller.

The examples in the $q on AngularJS docs section are great.

So by doing this, your controller doesn't have to wait around for the data. As soon as it's resolved

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

And in your controller you can do this:

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

Upvotes: 1

Related Questions