Friday, December 5, 2014

AngularJS - Intercept all ajax calls globally

Add following code in app module config section to handle success or error globally.

In below example i have handled 401 unauthorized error globally.

App.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"; //Post
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    var interceptor = ['$rootScope', '$q', function (scope, $q) {
        function success(response) {
            return response;
        }
        function error(response) {
            var status = response.status;
            console.log("site error: " + status);
            if (status == 401) {
                window.location.href = currentDomain;
                return;
            }
            // otherwise
            return $q.reject(response);
        }
        return function (promise) {
            return promise.then(success, error);
        }
    }];
    $httpProvider.responseInterceptors.push(interceptor);

}]);

2 comments:

  1. What ever the concepts I learned from this blog were also discussed indepth at online Angularjs training. Though this site is rich in content related to the subject such as examples and case-studies. Thanks

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete