Search code examples
angularjsangular-httpangular-factory

Angular - Having troubles receiving $http response from a factory


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

   });

Solution

  • 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.