Aborting ngResource using a promise object
Asked Answered
P

3

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?

Phip answered 13/2, 2015 at 10:20 Comment(3)
Apparently, it's not doing what you think it does when you pass a promise to $resource method: github.com/angular/angular.js/issues/7974Koski
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.Binford
@BradBarber thanks, that's the issue, please make your comment an answer so I can give you +100Phip
B
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.

Binford answered 17/2, 2015 at 12:20 Comment(1)
An update: It seems like this fix will be merged in 1.4.8 github.com/angular/angular.js/pull/12657Phip
K
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;
    });
});
Koski answered 13/2, 2015 at 11:2 Comment(1)
Thanks for you input, but I've tried that one as well jsfiddle.net/HB7LU/10983Phip
S
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

Supraorbital answered 27/2, 2015 at 15:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.