$ http POST response from service to controller

How to get a response from the Service in the lower case?

Services:

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 this case, I SEND the data through the Controller , and it works fine, but now I want the response to come to my controller.

How to achieve this?

+6
source share
2 answers

$http returns the promise :

Return a 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 success function to 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 that I can handle errors, etc., without passing these functions as well.

(NB: I have not tested the code above, so some modification may be required)

+10
source

what i usually do looks like this

 app.factory('call', ['$http', function($http) { //this is the key, as you can see I put the 'callBackFunc' as parameter function postOrder(dataArray,callBackFunc) { $http({ method: 'POST', url: 'example.com', data: dataArray }). success(function(data) { //this is the key callBackFunc(data); }). error(function(data, response) { console.log(response + " " + data); }); } return { postOrder:postOrder } }]); 

then in my controller i just call it

  $scope.postOrder = function() { call.getOrder($scope.data, function(data) { console.log(data); } } 

don't forget to inject "call" dependency injection into your controller

0
source

Source: https://habr.com/ru/post/971197/


All Articles