使用AngularJS的拦截器

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

AngularJS设置拦截器

在日常的web开发工程中,我们通常会在后台创建拦截器或者过滤器进行一些统一的权限控制或者统一编码等操作。然而当我们将前后端完全分离开之后( 前端只有JS代码,后端只有Java活着.net等一类语言代码),这个时候我们会有一些需求需要在前端统一进行处理,比如:统一一处地方处理系统错误代码,在一个地方对客户端所产生的请求进行状态处理。
其实 AngularJS给我们提供了这么一个功能,即 拦截器。对于AngularJS提供的拦截器可以从以下两个步骤出发进行使用。

针对我们的页面应用(module)创建APP

blapp.factory('blInterceptor', ["$cookies","$q","$rootScope",function ($cookies,$q,$rootScope) {
    var interceptor = {
        request: function (config) {
            //将COOKIE中纪录的状态数据每次请求时发送给后台
            config.headers["X-User-Id"] = $cookies.get("baid");
            config.headers["X-Token"] = $cookies.get("btoken")
            return config;
        },
        response: function(response) {
            if(response.data != null && response.data.code != 0){

                }
            }
            return response || $q.when(response);
        },
        responseError: function(response){
            console.log('responseError:' + response);
            if (response.status === 401) {
                authService.clear();
                window.location.href="#/login";
                return;
            }
            return $q.reject(response);
        }
    };
    return interceptor;

}])

将第一步中创建的拦截器配置在前端系统中

app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('blInterceptor');
  }

转载于:https://my.oschina.net/crazyharry/blog/1105207

你可能感兴趣的:(使用AngularJS的拦截器)