1

I've got a function in an Angular controller like so:

app.controller("UsersController", ["$scope",  "UserList", function($scope, UserList) {

    $scope.createUserSubmit = function(newUser) {

      UserList.createUser().success(function(data){
        console.log(data);
      });

    }

}]);

When the createUserSubmit() function is called, it calls another function to a function createUser() in a service UserList.

The service looks like this:

app.service("UserList", function() {
  this.createUser = function(){
    console.log("doing it");
    return "hi";
  }
});

Now, when this all runs, I get the "doing it" message logged, but then I get the following error and the console.log(data) does not log.

TypeError: undefined is not a function

Normally this type of error would be self explanatory, so either I'm being a moron or there's something confusing going on. As far as I can see, it is a function.

2
  • 3
    .success does not become available automatically from any return value, you need to return angular httpPromise for that Commented Jan 2, 2015 at 19:39
  • @PSL Thanks. This code above is abbreviated, but there's actually an http call to a database in the createUser() function. I then return the data from that call. If I can't do .success, how can I do a callback with the returned data? Commented Jan 2, 2015 at 19:43

1 Answer 1

7

You do not get success method from a string return value (which you are returning from your method createUser). You get it as a part of angular $http's httpPromise. If you are actually doing an ajax call with http just return $http call.

app.service("UserList", function($http) {
  this.createUser = function(){
    return $http('...');
  }
});

success and error methods are special function added to httpPromise inaddition to $q promise functions, it is an extension to $q promise.

And if you are looking to return data return a $q promise, which has a then method which is equivalent to success method. $q promise does not have success and error methods.

app.service("UserList", function($http) {
  this.createUser = function(){
    return $http('...').then(function(response){ 
             //Do your transformation and return the data
             return response.data;
           });
  }
});

and

UserList.createUser().then(function(data){
    console.log(data);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.