0

I have an angular factory doing some $http communication to the server and returning a string. However I get the Cannot read property 'then' of undefined error. I read here and here with similar problems however I was not able to resolve my problem.

This is the service code:

factory("availabilityService", ['$http', function ($http) {

    return {
        checkAvailability1: function (element, string) {
           // ..... some object creation code ......
            $http({
                method: 'POST',
                url: 'server/server.php',
                data: AvailableObj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
                .then(function successCallback(response) {
                    return response;

                }, function errorCallback(response) {
                });
        }
    }
}]);

Inside a controller:

$scope.checkAvailability = function (element, string) {
   availabilityService.checkAvailability1(element, string).then(function (response) { //on this line the error occurs 
       console.log(response);

   });
Community
  • 1
  • 1
Alex
  • 1,982
  • 4
  • 37
  • 70

1 Answers1

2

You need to return the promise returned by $http i.e add a 'return' in front of $http to get your code working like below :

return $http(...)
    .then(function successCallback(response) {
        return response;
    }, function errorCallback(response) {
    });

This is because, the function you have called from the controller should have a .then method on it i.e it should be a promise. checkAvailability1 in angular returns a promise which needs to be returned back by your function $http in the factory. You are just returning the response from the success callback which is not expected by your method in the controller.

Supradeep
  • 3,246
  • 1
  • 14
  • 28
  • Can you explain the logic behind this? I already returned the object itself and the response of the http request. – Alex Dec 27 '16 at 19:31
  • 2
    @undroid You are returning that response from the _callback method_, not from the function that actually made the $http request (checkAvailability1). That result never goes anywhere outside the scope of checkAvailability1. Return statements do not implicitly "bubble up" through the call stack. – Harris Dec 27 '16 at 19:33