I am trying to cancel pending api calls when the same api's are called again. I have dropdown onChange of which I am making my api call, here api call taking a lot of time to return data so i am cancelling all previous calls which are in pendingRequest array and keeping only the latest triggered call. please go through my code below
in my controller
angular.forEach($http.pendingRequests,function(r){
console.log(r.contractId);
if (r.contractId && r.contractId !== selectedContract) {
r.cancel.resolve('cancelled');
}
});
Here I am checking if the pending request is latest or not, by comparing current selected contract with pendingRequest array.
This is how I have written my service
getDashboardData:function(selectedContract) {
var deferred = $q.defer();
var cancel = $q.defer();
$rootScope.loaderOn=true;
var url = 'my_url_here';
$http.get(url, {
ignoreLoadingBar: true,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
cancel:cancel, //this is of type $q.defer();
contractId:selectedContract // here i assigned contrract id just to delete all pending api's other than current
}).then(function(data){
deferred.resolve(data.data);
$rootScope.loaderOn=false;
},function(error){
console.log(error);
return deferred.reject(err);
});
return deferred.promise;
}
I want to cancel or reject pending api calls. Any help will be appreciated thank you. Let me know if any other info required. Please correct me here.
I referred $http and doubt if cancel property exist in config object of $http.get function. You can use timeout property and use the value for cancelling the existing request.
I have replaced cancel property with timeout.
I hope below code helps.
// Declare the below objects in service level not inside getDashboardData function
var deferredObj = '';
var existingRequest = '';
getDashboardData: function(selectedContract) {
var deferred = $q.defer();
// Below condition will check to cancel the existing request
if (existingRequest) {
existingRequest = '';
deferredObj.resolve();
deferredObj = '';
} else {
deferredObj = $q.defer();
}
$rootScope.loaderOn=true;
var url = 'my_url_here';
existingRequest = $http.get(url, {
ignoreLoadingBar: true,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
**timeout : deferredObj.promise**, //this is of type $q.defer();
contractId:selectedContract // here i assigned contrract id just to delete all pending api's other than current
}).then(function(data){
deferred.resolve(data.data);
$rootScope.loaderOn=false;
},function(error){
console.log(error);
return deferred.reject(err);
});
return deferred.promise;
}