![](/img/trans.png)
[英]Controller not logging response from Nodejs using Angular $http service
[英]$http POST response from service to controller
如何在下面的案例中獲得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;
});
}
})
控制器:
updated_details = 'xyz';
ajaxService.updateTodoDetail(updated_details);
在上面這種情況下,我通過控制器POST數據 ,它工作正常,但現在我希望響應進入我的控制器。
如何實現?
$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
:
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.
})
我更喜歡第一個選項,所以我也可以處理錯誤等,而不會傳遞這些功能。
(注意:我沒有測試上面的代碼所以可能需要進行一些修改)
我通常做的就是這樣
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
}
}]);
然后在我的控制器中我只是稱之為
$scope.postOrder = function() {
call.getOrder($scope.data, function(data) {
console.log(data);
}
}
不要忘記將“call”服務的依賴注入插入控制器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.