如何在Angular JS中从控制器取消$ http调用? [英] How to cancel a $http call from controller in Angular JS?
本文介绍了如何在Angular JS中从控制器取消$ http调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对Angular还是很陌生,我想弄清楚如何通过单击按钮取消ajax调用,我编写了以下代码,请让我知道如何进一步添加它.预先感谢... !!!
I am quite new to Angular and i am trying to figure out how to cancel an ajax call from button click, I have written following code please let me know how to add it further. Thanks in advance...!!!
HTML
<a ng-click="cancelCall()" id="pods-cancel-search-button" title="Cancel" class="form-button primary" ><i class="fa fa-search fa-fw"></i>Cancel Search</a>
服务
paymentSearchApp.service('paymentSearchResponse',['$http', '$log', function($http, $log){
//var response = [];
return {
findResponse: (function(data){
return $http({
url:'data/result.json',
data:data,
dataType: 'JSON',
contentType: 'application/json; characterset=utf-8',
method: 'POST'
}).then(function(resp){
var response = resp;
return response.data;
},function(resp){
$log.error("ERROR occured");
});
})
};
return paymentSearchResponse;
}]);
控制器
paymentSearchApp.controller('paymentSearchCtrl', function (paymentSearchService,paymentSearchResponse, $scope) {
paymentSearchResponse.findResponse(requestPayLoadPacked).then(
function(response){
//operation on response
},function(){
alert("error in getting response from payment search service");
}
$scope.cancel = function(){
alert("cancel ajax call");
}
);
});
推荐答案
add additional parameter in your service:
paymentSearchApp.service('paymentSearchResponse',['$http', '$log', function($http, $log){
//var response = [];
return {
findResponse: (function(data, timeoutCanceler){
return $http({
url: 'data/result.json',
data: data,
timeout: timeoutCanceler.promise,
dataType: 'JSON',
contentType: 'application/json; characterset=utf-8',
method: 'POST'
}).then(function(resp){
var response = resp;
return response.data;
},function(resp){
$log.error("ERROR occured");
});
})
};
return paymentSearchResponse;
}]);
控制器:
paymentSearchApp.controller('paymentSearchCtrl', function (paymentSearchService, paymentSearchResponse, $scope, $q) {
var timeoutCanceler = $q.defer();
paymentSearchResponse.findResponse(requestPayLoadPacked, timeoutCanceler).then(
function(response){
//operation on response
},function(){
alert("error in getting response from payment search service");
};
$scope.cancelCall = function(){
timeoutCanceler.resolve();
alert("cancel ajax call");
}
);
});
我没有使用实时代码进行检查,但是应该给出指导原则
I did not check this with live code, but it should give a guide lines
这篇关于如何在Angular JS中从控制器取消$ http调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文