How to cancel $resource requests

萝らか妹 提交于 2019-11-28 17:15:22
Nikola M.

Answer by Gecko IT works for me, but I had to make some modifications in order to:

  • Enable resource ajax call to be canceled multiple times without need to recreate resource
  • Make resource backward compatible - This means that there is no need to change any application (Controller) code except resource factory
  • Make code JSLint compliant

This is complete service factory implementation (you just need to put proper module name):

'use strict';

/**
 * ResourceFactory creates cancelable resources.
 * Work based on: https://stackoverflow.com/a/25448672/1677187
 * which is based on: https://developer.rackspace.com/blog/cancelling-ajax-requests-in-angularjs-applications/
 */
/* global array */
angular.module('module_name').factory('ResourceFactory', ['$q', '$resource',
    function($q, $resource) {

        function abortablePromiseWrap(promise, deferred, outstanding) {
            promise.then(function() {
                deferred.resolve.apply(deferred, arguments);
            });

            promise.catch(function() {
                deferred.reject.apply(deferred, arguments);
            });

            /**
             * Remove from the outstanding array
             * on abort when deferred is rejected
             * and/or promise is resolved/rejected.
             */
            deferred.promise.finally(function() {
                array.remove(outstanding, deferred);
            });
            outstanding.push(deferred);
        }

        function createResource(url, options, actions) {
            var resource;
            var outstanding = [];
            actions = actions || {};

            Object.keys(actions).forEach(function(action) {
                var canceller = $q.defer();
                actions[action].timeout = canceller.promise;
                actions[action].Canceller = canceller;
            });

            resource = $resource(url, options, actions);

            Object.keys(actions).forEach(function(action) {
                var method = resource[action];

                resource[action] = function() {
                    var deferred = $q.defer(),
                    promise = method.apply(null, arguments).$promise;

                    abortablePromiseWrap(promise, deferred, outstanding);

                    return {
                        $promise: deferred.promise,

                        abort: function() {
                            deferred.reject('Aborted');
                        },
                        cancel: function() {
                            actions[action].Canceller.resolve('Call cancelled');

                            // Recreate canceler so that request can be executed again
                            var canceller = $q.defer();
                            actions[action].timeout = canceller.promise;
                            actions[action].Canceller = canceller;
                        }
                    };
                };
            });

            /**
             * Abort all the outstanding requests on
             * this $resource. Calls promise.reject() on outstanding [].
             */
            resource.abortAll = function() {
                for (var i = 0; i < outstanding.length; i++) {
                    outstanding[i].reject('Aborted all');
                }
                outstanding = [];
            };

            return resource;
        }

        return {
            createResource: function (url, options, actions) {
                return createResource(url, options, actions);
            }
        };
    }
]);

Usage is the same as in Gecko IT example. Service factory:

'use strict';

angular.module('module_name').factory('YourResourceServiceName', ['ResourceFactory', function(ResourceFactory) {
    return ResourceFactory.createResource('some/api/path/:id', { id: '@id' }, {
        create: {
            method: 'POST'
        },
        update: {
            method: 'PUT'
        }
    });
}]);

Usage in controller (backward compatible):

var result = YourResourceServiceName.create(data);
result.$promise.then(function success(data, responseHeaders) {
    // Successfully obtained data
}, function error(httpResponse) {
    if (httpResponse.status === 0 && httpResponse.data === null) { 
        // Request has been canceled
    } else { 
        // Server error 
    }
});
result.cancel(); // Cancels XHR request

Alternative approach:

var result = YourResourceServiceName.create(data);
result.$promise.then(function success(data, responseHeaders) {       
    // Successfully obtained data
}).catch(function (httpResponse) {
    if (httpResponse.status === 0 && httpResponse.data === null) { 
        // Request has been canceled
    } else { 
        // Server error 
    }
});
result.cancel(); // Cancels XHR request

Further improvements:

  • I don't like checking if request has been canceled. Better approach would be to attach attribute httpResponse.isCanceled when request is canceled, and similar for aborting.

(for Angular 1.2.28+)Hello All , I just wanted to make that easy to understand , how I handled that issue is as follows :

Here I declare timeout parameter

$scope.stopRequestGetAllQuestions=$q.defer();

then in I use it as follows

return $resource(urlToGet, {}, {get:{ timeout: stopRequestGetAllQuestions.promise }});

and if I want to stop previous $resource calls I just resolve this stopRequestGetAllQuestions object that is all.

stopRequestGetAllQuestions.resolve();

but if I want to stop previous ones and start a new one $resource call then I do this after stopRequestGetAllQuestions.resolve();:

stopRequestGetAllQuestions = $q.defer(); 

There are quite a lot of examples currently out there. The following two I've found quite informative:

THis one shows an example how to deal with both $resource and $http requests: https://developer.rackspace.com/blog/cancelling-ajax-requests-in-angularjs-applications/

and

This one is simpler and is only for $http: http://odetocode.com/blogs/scott/archive/2014/04/24/canceling-http-requests-in-angularjs.aspx

Hi I made a custom handler based on https://developer.rackspace.com/blog/...

.factory('ResourceFactory', ["$q", "$resource", function($q, $resource) {
    function createResource(url, options, actions) {
        var actions = actions || {},
        resource,
        outstanding = [];

        Object.keys(actions).forEach(function (action) {
            console.log(actions[action]);
            var canceller = $q.defer();
            actions[action].timeout = canceller.promise;
            actions[action].Canceller = canceller;
        });

        resource = $resource(url, options, actions);

        Object.keys(actions).forEach(function (action) {
            var method = resource[action];

            resource[action] = function () {
                var deferred = $q.defer(),
                promise = method.apply(null, arguments).$promise;

                abortablePromiseWrap(promise, deferred, outstanding);

                return {
                    promise: deferred.promise,

                    abort: function () {
                        deferred.reject('Aborted');
                    },
                    cancel: function () {
                        console.log(actions[action]);
                        actions[action].Canceller.resolve("Call cancelled");
                    }
                };
            };
        });

        /**
        * Abort all the outstanding requests on
        * this $resource. Calls promise.reject() on outstanding [].
        */
        resource.abortAll = function () {
            for (var i = 0; i < outstanding.length; i++) {
                outstanding[i].reject('Aborted all');
            }
            outstanding = [];
        };

        return resource;
    }

    return {
        createResource: function (url, options, actions) {
            return createResource(url, options, actions);
        }
    }
}])

function abortablePromiseWrap(promise, deferred, outstanding) {
    promise.then(function () {
        deferred.resolve.apply(deferred, arguments);
    });

    promise.catch(function () {
        deferred.reject.apply(deferred, arguments);
    });
    /**
    * Remove from the outstanding array
    * on abort when deferred is rejected
    * and/or promise is resolved/rejected.
    */
    deferred.promise.finally(function () {
        array.remove(outstanding, deferred);
    });
    outstanding.push(deferred);
}


//Usage SERVICE
factory("ServiceFactory", ["apiBasePath", "$resource", "ResourceFactory", function (apiBasePath, $resource, QiteResourceFactory) {
    return ResourceFactory.createResource(apiBasePath + "service/:id", { id: '@id' }, null);
}])

//Usage Controller
var result = ServiceFactory.get();
console.log(result);
result.promise.then(function (data) {       
    $scope.services = data;
}).catch(function (a) {
    console.log("catch", a);
})
//Actually cancels xhr request
result.cancel();

One solution is to re-craete the resource every time you need it.

// for canceling an ajax request
$scope.canceler = $q.defer();

// create a resource
// (we have to re-craete it every time because this is the only
// way to renew the promise)
function getAPI(promise) {
    return $resource(
        'index.html', {}, {
            get: {
                method: 'GET',
                timeout: promise
            }
        }
    );
}

$scope.fetchData = function() {

    // abort previous requests if they are still running
    $scope.canceler.resolve();

    // create a new canceler
    $scope.canceler = $q.defer();

    // instead of using "API.get" we use "getAPI().get"
    getAPI( $scope.canceler.promise ).get({}, function() {
        $scope.actions.push('completed');
        $scope.pending = 0;
    }, function() {
        $scope.actions.push('aborted');
    });

}

In our attempt to solve this task we got to the following solution:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Cancel resource</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-resource.js"></script>
  <script>
angular.module("app", ["ngResource"]).
factory(
  "services",
  ["$resource", function($resource)
  {
    function resolveAction(resolve)
    {
      if (this.params)
      {
        this.timeout = this.params.timeout;
        this.params.timeout = null;
      }

      this.then = null;
      resolve(this);
    }

    return $resource(
      "http://md5.jsontest.com/",
      {},
      {
        MD5:
        {
          method: "GET",
          params: { text: null },
          then: resolveAction
        },
      });
  }]).
controller(
  "Test",
  ["services", "$q", "$timeout", function(services, $q, $timeout)
  {
    this.value = "Sample text";
    this.requestTimeout = 100;

    this.call = function()
    {
      var self = this;

      self.result = services.MD5(
      {
        text: self.value,
        timeout: $q(function(resolve)
        {
          $timeout(resolve, self.requestTimeout);
        })
      });
    }
  }]);
  </script>
</head>
<body ng-app="app" ng-controller="Test as test">
  <label>Text: <input type="text" ng-model="test.value" /></label><br/>
  <label>Timeout: <input type="text" ng-model="test.requestTimeout" /></label><br/>
  <input type="button" value="call" ng-click="test.call()"/>
  <div ng-bind="test.result.md5"></div>
</body>
</html>

How it works

  1. $resource merges action definition, request params and data to build a config parameter for an $http request.
  2. a config parameter passed into an $http request is treated as a promise like object, so it may contain then function to initialize config.
  3. action's then function may pass timeout promise from params into the config.

Please look at "Cancel Angularjs resource request" for details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!