$http POST response from service to controller

Jay picture Jay · Jun 23, 2014 · Viewed 11.9k times · Source

How to get the response from Service in below case??

Service:

app.factory('ajaxService', function($http) {
    updateTodoDetail: function(postDetail){
        $http({
            method: "POST",
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            url: post_url,
            data: $.param({detail: postDetail})
        })
        .success(function(response){
            //return response;
        });
    }
})

Controller:

updated_details = 'xyz';
ajaxService.updateTodoDetail(updated_details);

In th above case, i POST the data through Controller and it was working fine but now i want the response to come in my Controller.

How to achive that??

Answer

Jorg picture Jorg · Jun 23, 2014

$http returns a promise:

Return the promise

updateTodoDetail: function(postDetail){
    return $http({
        method: "POST",
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        url: post_url,
        data: $.param({detail: postDetail})
    });

So you can do

ajaxService.updateTodoDetail(updated_details).success(function(result) {
    $scope.result = result //or whatever else.
}

Alternatively you can pass the successfunction into updateTodoDetail:

updateTodoDetail: function(postDetail, callback){
    $http({
        method: "POST",
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        url: post_url,
        data: $.param({detail: postDetail})
    })
    .success(callback);

So your controller has

ajaxService.updateTodoDetail(updated_details, function(result) {
    $scope.result = result //or whatever else.
})

I would prefer the first option so I could handle errors etc as well without passing in those functions too.

(NB: I haven't tested the code above so it might require some modification)