angularJS创建拦截注入$httpProvider、interceptor 、auth

angularJS创建拦截注入,为每个$http请求添加auth权限请求:

var app = angular.module("myApp", ["ngRoute", "ngResource"])
    .constant('ACCESS_LEVELS',{
        PUB:1,
        USER:2
    })
    .config(["$routeProvider", "$httpProvider","ACCESS_LEVELS", function ($routeProvider, $httpProvider,ACCESS_LEVELS) {

        //设置http头
        $httpProvider.defaults.headers.common["X-Response-Code-By"] = "Angular1.5.8";

        var interceptor = function ($q, $rootScope, auth) {
            return {
                'response': function (res) {
                    //登录成功,设置authkey
                    if (res.config.url.indexOf('/api/v1/login')!=-1) {
                        auth.set(res.data.auth);
                    }
                    return res;
                },
                'responseError': function (rejection) {
                    switch (rejection.status) {
                        case 401:
                            if (res.config.url.indexOf('/api/v1/login')!=-1) {
                                // 如果当前不是在登录页面
                                $rootScope.$broadcast('auth:loginRequired');
                            }
                            break;
                        case 403:
                            $rootScope.$broadcast('auth:forbidden');
                            break;
                        case 404:
                            $rootScope.$broadcast('page:notFound');
                            break;
                        case 500:
                            $rootScope.$broadcast('server:error');
                            break;

                    }
                    return $q.reject(rejection);
                },
                'request': function (config) {

                    //为每条服务器请求加入auth权限
                    if(config.url.indexOf("api/v1/") > -1){
                        if(config.url.indexOf("?") != -1){
                            config.url += "&auth="+auth.get();
                        }else{
                            config.url += "?auth="+auth.get();
                        }

                    }
                    return config;
                },
                'requestError': function (rejection) {
                    if (canRecover(rejection)) {
                        return responseOrNewPromise
                    }
                    return $q.reject(rejection);
                },
            };
        };


        $httpProvider.interceptors.push(interceptor);

        //路由
        $routeProvider
            .when("/", {
                templateUrl: "view/main.html",
                controller: "controllerMain",
                access_level:ACCESS_LEVELS.PUB
            })
            .when("/list/:id", {
                templateUrl: "view/list.html",
                controller: "controllerList",
                access_level:ACCESS_LEVELS.PUB
            })
            .when("/about", {
                templateUrl: "view/about.html",
                controller: "controllerAbout",
                access_level:ACCESS_LEVELS.PUB
            })
            .when("/contact", {
                templateUrl: "view/contact.html",
                controller: "controllerContact",
                access_level:ACCESS_LEVELS.PUB
            })
            .when("/login", {
                templateUrl: "view/login.html",
                controller: "controllerLogin",
                access_level:ACCESS_LEVELS.PUB
            })
            .when("/register", {
                templateUrl: "view/register.html",
                controller: "controllerRegister",
                access_level:ACCESS_LEVELS.PUB
            })
            .when("/uc_enter", {
                templateUrl: "view/uc_enter.html",
                controller: "controllerUcenter",
                access_level:ACCESS_LEVELS.USER
            })
            .otherwise({redirectTo: '/'})
    }])
    .run(function ($rootScope, $location,auth,cookieUtils,ajax) {
        auth.set(cookieUtils.get("auth"));

        $rootScope.title = "本地网站";
        $rootScope.keywords = "网站的关键词";
        $rootScope.description = "网站的描述";

        $rootScope.isActive = function (score) {
            return score == $location.path();
        };

        //判断是否登录
        $rootScope.isLogin = function(){
            return !auth.get();
        }

        //路由开始
        $rootScope.$on('$routeChangeStart', function (evt, next, current) {

            //boot菜单选择器
            if($(".navbar-toggle").attr('aria-expanded') == "true"){
                $(".navbar-toggle").click();
            }
            if(next.$$route.access_level == 2 && auth.get().length == 0){
                toast("请先登录!");
                $location.path("/login");
            }
        });

        //路由成功
        $rootScope.$on('$routeChangeSuccess', function (evt, next, previous) {

        });

        //路由错误
        $rootScope.$on('$routeChangeError', function (current, previous, rejection) {
            c('$routeChangeError')
            c(current)
            c(previous)
            c(rejection)
        });

        //登出
        $rootScope.loginOut = function(){
            ajax.get("/api/v1/loginOut",{})
                .success(function(data){
                    if(data.response_code == 1){
                        auth.del();
                        if(toast(data.response_err)){
                            $location.path("/");
                        }

                    }
                })
        };
    })
.factory("UserSerice",function($q,$http,ajax){
    var _url = '/api/v1/user/';

    return {
        get:function(id,param){
            var defer = $q.defer();
            $http.get(ajax.parseParam(_url + id,param))
                .success(function(data){
                    defer.resolve(data);
                })
                .error(function(data){
                    defer.reject(data);
                })
            return defer.promise;
        },
        save:function(param){
            var defer = $q.defer();
            $http.post(_url,param)
                .success(function(data){
                    defer.resolve(data);
                })
                .error(function(data){
                    defer.reject(data);
                })
            return defer.promise;
        },
        put:function(id,param){
            var defer = $q.defer();
            $http.put(_url + id,param)
                .success(function(data){
                    defer.resolve(data);
                })
                .error(function(data){
                    defer.reject(data);
                })
            return defer.promise;
        }

    }
})
//用户权限校验
.factory("auth", function (cookieUtils) {
    var auth = '';
    return {
        set: function (a) {
            auth = a;
            cookieUtils.set('auth',typeof a == "string" ? a : '');
        },
        get: function () {
            return auth;
        },
        del:function(){
            auth = '';
            cookieUtils.del('auth');
            cookieUtils.del('user_name');
            cookieUtils.del('user_pwd');
        }
    }
})

 

 

 

 

 

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |