How to intercept every Ajax Request with Angular JS

I need to intercept every Ajax Request to verify if the server responded with a 401 Unauthorized because the session expired and redirect to the login page so the user don't think the app stopped working. I can do this the following way using JQuery:

$( document ).ajaxComplete(function( event, xhr, settings ) {
   if(xhr.errorCode == 401 || xhr.responseText === "unauthorized") {
    location.href = "/Login";
   }
});

How can i do this with Angular JS?

Answers


You can set the $interceptor on application config()

        .config(['$httpProvider', function($httpProvider) {
        $httpProvider.interceptors.push(['$location', '$q',  function($location, $q) {
            return {
                'request': function(request) {    
                    return request;
                },
                'responseError': function(response) {
                    if (response.status === 401) {
                        // do stuff
                    }
                    // otherwise, default behaviour
                    return $q.reject(response);
                }
            };
        }]);
    }])

Use httpInterceptor. Very similar question was answered awhile ago. You should then be interested in 'response' hanndler and add your specific logic there.


Make a single function that you use to make all your calls, you only have to handle errors in one place instead of many

function makeCall(obj, cb) {
    $http({
        method: obj.method,
        url: obj.url,
        data: obj.data || {}
    }, function(res) {
        // non error statuses get handled here
    }, function(res) {
        // error statuses get handled here
    })
}

Need Your Help

Format JSON file to be read localhost?

javascript json

I dont know if I am formatting my .json wrong but I am using backbone.js and cannot pass in the url to my json file.

Get debug information from PE or PDB file

visual-studio-2010 debugging pdb-files portable-executable

I don't want to tell the whole story but all in all it would lead to this simple question: