码迷,mamicode.com
首页 > Web开发 > 详细

[AngularJS] Using AngularJS interceptors with $http

时间:2015-01-15 07:04:20      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

[AngularJS] Using AngularJS interceptors with $http

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/4225381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!