I am trying to stop all the pending requests when a state change occurs.The below code works fine with $http but not with $resource.
var cancel=$q.defer();
$http.get('api/cafservicestatus',{timeout:cancel.promise,cancel:cancel}).then(onsuccess,onerror);
function onsuccess(result) {
console.log(result)
}
function onerror(error) {
console.log(error)
}
function stopHttp() {
$http.pendingRequests.forEach(function(request) {
if (request.cancel) {
request.cancel.resolve();
}
});
}
But this code doesn't work with $resource Here is a sample code for $resource
$resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true,timeout:$q.defer().promise,cancel:$q.defer()},
'get': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
}
return data;
}
},
'update': { method:'PUT' }
});
How can I stop all requests using $resource
I have figured out this one.You must add a cancellable:true to your request and cancel the request in your controller using $cancelRequest()method of $resource.
for example, In your case
$resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true,cancellable:true},
'get': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
}
return data;
}
},
'update': { method:'PUT' }
});
and inside your controller
var aborted= YourService.query();
//and later on state change
$scope.$on('$stateChangeSuccess',function(event){
aborted.$cancelRequest();
}
);