Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop request in angularjs interceptor

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');
});
like image 935
vipulsodha Avatar asked Aug 24 '14 15:08

vipulsodha


People also ask

How do you stop an interceptor request?

If you wanna cancel requests after a certain timeout you can use rxjs timeout operator in intercepter, and it will work for every requests.

What is the use of interceptor in Angularjs?

HTTP Interceptors are used for adding custom logic for authentication, authorization, session/state management, logging, modifying Response, URL rewriting, Error handling, Caching, adding custom header, timestamp in the request /response, encrypt and decrypt the request and response information or manipulate the ...


Video Answer


1 Answers

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.

like image 146
jtheoof Avatar answered Sep 28 '22 03:09

jtheoof