KpsLok
KpsLok

Reputation: 903

Factory doesnt return http data response

Im trying to get http post data response using the code below (it is working).

app.factory('LoginService', function($http, $location) {

return {
    existUser: function(loginObj) 
    {

        $http({

            method: 'POST',
            url: server + '/login',
            headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
            data: 'json=' + JSON.stringify(loginObj)

        }).then(function successCallback(response) {

                return response.data;

            }, function errorCallback(response) {
                console.log(response);
                console.log("erro!");

            }); 

    }
}

});

Inside of my controller, i have:

LoginService.existUser(loginObj).then(function (data){
    console.log(data);
});

And i got the error:

Cannot read property 'then' of undefined

What is wrong?

Upvotes: 0

Views: 82

Answers (1)

Enver Dzhaparoff
Enver Dzhaparoff

Reputation: 4421

Your return response.data; returns result of then function, not existUser! Modify your code like below:

app.factory('LoginService', function($http, $location) {

   return {
     existUser: function(loginObj) 
       {
          return $http({
            method: 'POST',
            url: server + '/login',
            headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
            data: 'json=' + JSON.stringify(loginObj)
          })
       }
    }

});

In this case, existUser method returns promise object, that has .then method

Upvotes: 1

Related Questions