简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM