pranay anand pranay anand - 1 month ago 15
HTTP Question

How to cancel a $http call from controller in Angular JS?

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>


Service

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;


}]);


Controller

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");

}
);

});

Answer

see How to cancel an $http request in AngularJS?.

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;
}]);

controller:

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