hugo der hungrige
hugo der hungrige

Reputation: 12912

How to abort a request in a http-interceptor?

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.

Upvotes: 0

Views: 3850

Answers (1)

TheSharpieOne
TheSharpieOne

Reputation: 25726

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);
        }       
    };
});

Upvotes: 3

Related Questions