There is a Resource that receives information about the object. There is a lot of information and depending on the selected object, it can be calculated long enough.

$scope.currentInfo = null; Info = $resource('/info'); $scope.getInfo = function(id) { Info.post({id: id}).$promise.then(function(response) { $scope.currentInfo = response.data; }) } 

At some point, the user can request information about another object, without waiting for an answer to the first request. How, then, to cancel the first request, so that it does not overwrite $ scope.currentInfo , if the answer comes later than the second request?

2 answers 2

As stated in the documentation , the request can be canceled using the $cancelRequest function. To do this, add the cancellable option to the method.

This parameter works for the version starting from 1.5.0 .

An example on jsfiddle .

 angular.module('ExampleApp', ['ngResource']) .controller('ExampleController', function(ExampleService) { var vm = this; //Массив для отображения информации о запросах vm.request = []; vm.start = function() { vm.cancel(); //Отменяем предыдущий запрос ExampleService.getData(1).$promise .then(function() { console.log('success'); }) .catch(function(data) { console.log('catch', data); vm.request.push(data); }); }; vm.cancel = function() { if (ExampleService.getData.$promise) ExampleService.getData.$promise.$cancelRequest(); }; }) .service('ExampleService', function($resource) { var Example = $resource("/data/:id", { id: "@id" }, { // Let's make the `query()` method cancellable query: { method: 'get', isArray: true, cancellable: true } }); return { getData: function(id) { // Сохраняем промис для отмены this.getData.$promise = Example.query({ id: id }); return this.getData.$promise; } } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular-resource.js"></script> <div ng-app="ExampleApp"> <div ng-controller="ExampleController as vm"> <button ng-click="vm.start()"> Start Request </button> <button ng-click="vm.cancel()"> Cancel Request </button> <div ng-repeat="req in vm.request"> <pre>{{$index}}: status = {{req.status}} statusText = {{req.status==-1?"Cancelled":req.statusText}}</pre> </div> </div> </div> 

Unfortunately, the snippet does not work. But the code is working and jsfiddle too.

    When using the $ http service, for example, $ http.get ('urltoresource', {timeout: myPromise}), the timeout parameter accepts promises; if it is resolved, the request will be terminated. This is just in case, if there is no analogue with the resource. You can create promis using the $ q service