4

I've recently learned that ngResource request can be aborted either by specifying a timeout in ms or passing a deferred object.

The second solution does not seem to work for me, and I have no idea what I'm doing wrong. I've created a fiddle to demonstrate the problem http://jsfiddle.net/HB7LU/10977/

var myApp = angular.module('myApp',['ngResource']);

myApp.factory('myResource', function($resource) {
    return {
      getResource: function (aborter) {
        var resource = $resource(
            'http://api.openweathermap.org/data/2.5/weather?q=London,uk', {}, {
          query: {
            isArray: false,
            timeout: aborter.promise
          }
        });

        return resource;
      }
    };
});

myApp.controller('MyCtrl', function($scope, $q, $log, $timeout, myResource) {
    var aborter = $q.defer();
    setTimeout(function() {
       $log.info('Aborting...');
       aborter.resolve();
    }, 10);
    myResource.getResource(aborter).query().$promise.then(function(data) {
        $scope.data = data;
    });
});

I want to avoid sending multiple request at the time (I want to cancel the previous by calling aborter.resolve().

I was following this solution Angular $http : setting a promise on the 'timeout' config Could you please advice me why it does not work?

Community
  • 1
  • 1
Jan Vorcak
  • 19,261
  • 14
  • 54
  • 90
  • Apparently, it's not doing what you think it does when you pass a promise to $resource method: https://github.com/angular/angular.js/issues/7974 – Wawy Feb 13 '15 at 13:51
  • 1
    It looks like it's an open issue with Angular 1.3: https://github.com/angular/angular.js/issues/9332 You're jsfiddle works if you drop back to 1.2.28. – Brad Barber Feb 16 '15 at 14:23
  • 1
    @BradBarber thanks, that's the issue, please make your comment an answer so I can give you +100 – Jan Vorcak Feb 17 '15 at 08:32

3 Answers3

2

It looks like it's an open issue with Angular 1.3: github.com/angular/angular.js/issues/9332 You're jsfiddle works if you drop back to 1.2.28.

Brad Barber
  • 2,953
  • 1
  • 19
  • 18
  • 1
    An update: It seems like this fix will be merged in 1.4.8 https://github.com/angular/angular.js/pull/12657 – Jan Vorcak Oct 09 '15 at 06:38
0

Try using $timeout, instead of setTimeout, since that will take care of making sure your resolve is captured by angular $digest cycle.

myApp.controller('MyCtrl', function($scope, $q, $log, $timeout, myResource) {
    var aborter = $q.defer();
    $timeout(function() {
       $log.info('Aborting...');
       aborter.resolve();
    }, 10);
    myResource.getResource(aborter).query().$promise.then(function(data) {
        $scope.data = data;
    });
});
Wawy
  • 6,259
  • 2
  • 23
  • 23
0

try to change this line of ngResource source code:

httpConfig[key] = copy(value);

in

httpConfig[key] = key !== 'timeout' ? copy(value) : value;

the problem is the copied promise