0

In an app I have the following url structure for the api:

// public
public/url-xyz

// private
dashboard/url-xyz

Knowing that, and trying to save unnecessary requests: What would be the best way to cancel a request? What I've tried so far is:

angular.module('mymod').factory('httpInterceptors', function ($injector, $q, httpBuffer)
{

    return {
        request: function (config)
        {
            var url = config.url;
            if (url.match('/dashboard/')) {
                    // immediately cancel request
                    var canceler = $q.defer();
                    config.timeout = canceler.promise;
                    canceler.reject(config);

                    // logout and go to login-page immediately
                    // ...                       
            }

            // request config or an empty promise
            return config || $q.when(config);
        }       
    };
});

But this can lead to problems with $ressource as it expects an array and gets an object as a response, if its request is canceled like that.

hugo der hungrige
  • 12,382
  • 9
  • 57
  • 84
  • funny enough i found the same question via google, but I can't find it via the stacoverflow search and am thus unable to mark my question as a duplicate: http://stackoverflow.com/questions/22090792/cancelling-a-request-with-a-http-interceptor – hugo der hungrige Sep 25 '14 at 19:02

1 Answers1

3

You should be able to return $q.reject([reason])

angular.module('mymod').factory('httpInterceptors', function ($injector, $q, httpBuffer)
{

    return {
        request: function (config)
        {
            var url = config.url;
            if (url.match('/dashboard/')) {
                    // immediately cancel request
                    return $q.reject(config);

                    // logout and go to login-page immediately
                    // ...                       
            }

            // request config or an empty promise
            return config || $q.when(config);
        }       
    };
});
TheSharpieOne
  • 25,646
  • 9
  • 66
  • 78
  • 1
    This works but breaks a lot of third party modules (e.g. restangular, all sorts of global loading spinners, http-authentication modules, ect.) using an interceptor as well – hugo der hungrige Sep 25 '14 at 19:28
  • 1
    Yes, the interceptors will intercept all of the `$http` requests, if you reject them it will have impacts. Some of the tools are not smart enough to look for rejected promises and always assume that a request will have a successful response. – TheSharpieOne Sep 25 '14 at 20:07