5

It seems pretty clear how to set a global method to abort http requests. Something along the lines of

$scope.canceller = $q.defer();
var API = $resource('http:/foo.com', {}, {get: { 
    method:'GET',
    timeout:$scope.canceller.promise
}});

$scope.abortRequests = function() {
    $scope.canceller.resolve();
}

However, I want to be able to abort only specific requests. I could define separate resource for the requests I need to be able to abort, but that's pretty ugly. Is there any way I can pass in a parameter or something when I call the $resource that could allow the timeout to be conditional? Maybe along the lines of:

var API = $resource('http:/foo.com', {}, {get: { 
    method:'GET',
    timeout:function() { if (FOO) { return $scope.canceller.promise; }}
}});

But how do I access FOO?

Thanks for any insight!

Greg Michalec
  • 849
  • 3
  • 10
  • 17
  • I couldn't find any way of doing this with stock angular, so I've applied the patch from this pull request: https://github.com/angular/angular.js/pull/5613 - it seems to work fine. Now, using the above code example, I can just call API.$abort(); to abort the request. – Greg Michalec Feb 10 '14 at 23:08

1 Answers1

0

Perhaps you can try to wrap your $resource as model and access data via service calls like this. The example shows, that only $routeChangeStart resolves the timeout promise. So it's somehow conditional, as you mentioned.

app.factory('fooModel', function ($resource) {
    return function (canceler) {
        return $resource('http:/foo.com', {},
            {
                query:  {method:'GET', timeout: canceler.promise },
            }
        );
    };
});

app.service('fooService', function (fooModel, $q, $rootScope) {
    this.getBar = function(whatEver) {
        var deferred = $q.defer();
        var params = {};
        var canceler = $q.defer();

        $rootScope.$on('$routeChangeStart', function () {
            canceler.resolve();
        });

        fooModel(canceler).query(
            params,
            function(response) {
                deferred.reject(response);
            }, function(error) {
                deferred.reject(error);
            });
        return deferred.promise;
    };
});
xam.esurk
  • 133
  • 4