Stop request in angularjs interceptor

vipulsodha picture vipulsodha · Aug 24, 2014 · Viewed 14.7k times · Source

How can I stop a request in Angularjs interceptor.

Is there any way to do that?

I tried using promises and sending reject instead of resolve !

.factory('connectionInterceptor', ['$q', '$timeout',
   function($q, $timeout) {
    var connectionInterceptor = {
        request: function(config) {
            var q = $q.defer();
            $timeout(function() {
                q.reject();
            }, 2000)
            return q.promise;
            // return config;
        }
    }
    return connectionInterceptor;
  }
])
.config(function($httpProvider) {
   $httpProvider.interceptors.push('connectionInterceptor');
});

Answer

jtheoof picture jtheoof · Aug 12, 2016

I ended up bypassing angular XHR call with the following angular Interceptor:

function HttpSessionExpiredInterceptor(sessionService) {
    return {
        request: function(config) {
            if (sessionService.hasExpired()) {
                /* Avoid any other XHR call. Trick angular into thinking it's a GET request.
                 * This way the caching mechanism can kick in and bypass the XHR call.
                 * We return an empty response because, at this point, we do not care about the
                 * behaviour of the app. */
                if (_.startsWith(config.url, '/your-app-base-path/')) {
                    config.method = 'GET';
                    config.cache = {
                        get: function() {
                            return null;
                        }
                    };
                }
            }

            return config;
        }
    };
}

This way, any request, POST, PUT, ... is transformed as a GET so that the caching mechanism can be used by angular. At this point, you can use your own caching mechanism, in my case, when session expires, I do not care anymore about what to return.