[AngularJS] Using AngularJS interceptors with $http

Sometimes you might need to modify HTTP requests and responses. This could be for a variety of reasons such as adding global logic handling for HTTP errors. With interceptors, you can easily accomplish this in your Angular applications.

var interceptor = function ($q, $location) {
    return {
        request: function (config) {
            console.log(config);
            return config;
        },

        response: function (result) {
            console.log(‘Repos:‘);
            result.data.splice(0, 10).forEach(function (repo) {
                console.log(repo.name);
            })
            return result;
        },

        responseError: function (rejection) {
            console.log(‘Failed with‘, rejection.status, ‘status‘);
            if (rejection.status == 403) {
                $location.url(‘/login‘);
            }

            return $q.reject(rejection);
        }
    }
};

angular.module(‘app‘, [])
    .config(function ($httpProvider) {
        $httpProvider.interceptors.push(interceptor);
    })
    .run(function ($http) {
        $http.get(‘https://api.github.com/users/bclinkinbeard/reposefw‘);
    });

 

In a lot of cases, interceptor can be used for Auth.

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。