RSS 2.0
Sign In
# Monday, February 2, 2015

We needed to cancel angularjs $resource requests but have found that it's not trivial, though $http service has timeout property that allows to pass a promise that aborts a request when resolved.

So, we took a little time and divised a code to be able to cancel such requests.

Consider a sample (nesterovsky-bros/angularjs-api/master/angularjs/cancel-resource.html):

<!DOCTYPE html>
  <meta charset="utf-8" />
  <title>Cancel resource</title>
  <style type="text/css">
    .ng-cloak { display: none; }
  <script src="angular.js"></script>
  <script src="angular-resource.js"></script>
angular.module("app", ["ngResource"]).
  ["$resource", function($resource)
    function resolveAction(resolve) // #1
      if (this.params)
        this.timeout = this.params.timeout;
        this.params.timeout = null;

      this.then = null;

    return $resource(
          method: "GET",
          params: { text: null },
          then: resolveAction // #2
  ["services", "$q", "$timeout", function(services, $q, $timeout)
    this.value = "Sample text";
    this.requestTimeout = 100; = function()
      var self = this;

      self.result = services.MD5(
        text: self.value,
        timeout: $q(function(resolve) // #3
          $timeout(resolve, self.requestTimeout);
<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=""/>
  <div ng-bind="test.result.md5"></div>

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.

In code it looks like this:

  • #2 - here we attach then function to the action MD5;
  • #1 - then function implementation:
    • move timeout promise, if any, from params to config;
    • reset then function from config to prevent resolve recursion (remember that we deal with merged config object, which is different from action definition);
    • call resolve function.
  • #3 - While calling services.MD5() we pass a timeout parameter as a promise that should be resolved to abort the request.

That's all. The demo can be found at cancel-resource.html

Monday, February 2, 2015 11:05:36 AM UTC  #    Comments [0] -
AngularJS | javascript
Comments are closed.
<July 2024>
Total Posts: 387
This Year: 3
This Month: 0
This Week: 0
Comments: 1371
Locations of visitors to this page
The opinions expressed herein are our own personal opinions and do not represent our employer's view in anyway.

© 2024, Nesterovsky bros
All Content © 2024, Nesterovsky bros
DasBlog theme 'Business' created by Christoph De Baene (delarou)