简体   繁体   中英

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?

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

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