Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$http POST response from service to controller

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??

like image 743
Jay Avatar asked Jun 23 '14 03:06

Jay


1 Answers

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

like image 96
Jorg Avatar answered Sep 17 '22 22:09

Jorg