$ http POST从服务到控制器的响应 [英] $http POST response from service to controller
本文介绍了$ http POST从服务到控制器的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在以下情况下如何获得服务部门的答复?
How to get the response from Service in below case??
服务:
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;
});
}
})
控制器:
updated_details = 'xyz';
ajaxService.updateTodoDetail(updated_details);
在上述情况下,我通过Controller发布数据,并且工作正常,但现在我希望响应出现在Controller中.
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.
如何实现?
推荐答案
$http
返回承诺:
兑现诺言
updateTodoDetail: function(postDetail){
return $http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: post_url,
data: $.param({detail: postDetail})
});
所以你可以做
ajaxService.updateTodoDetail(updated_details).success(function(result) {
$scope.result = result //or whatever else.
}
或者,您可以将success
函数传递给updateTodoDetail
:
Alternatively you can pass the success
function 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);
您的控制器有
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)
这篇关于$ http POST从服务到控制器的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文