想针对angular的$http请求错误码做统一处理(比如用户未登录时,跳转到登录页)
而网上的关于$httpProvider interceptor的案例,都是在具体的module.config中进行配置的(如果项目中module多的话,岂不是要一个个去配置?)
目前,我的项目代码结构是,一个JS文件定义一个module,主模块依赖这些子module。想知道怎么将$http错误码的拦截处理,配置到所有的module中?
//依赖的业务模块
var SERVICE_DEPENDENCIES = ['module1','module2'];
//依赖的公共组件模块
var COMMON_DEPENDENCIES = ['ui.router','ngCookies','ngAnimate','toastr'];
//声明主模块:并合并和引入相关模块
var mainApp = angular.module('mainApp', COMMON_DEPENDENCIES.concat(SERVICE_DEPENDENCIES));
//主模块配置
mainApp.config(['$httpProvider',function($httpProvider){
//为http添加过滤器
$httpProvider.interceptors.push('myHttpInterceptor');
}]);
//过滤器定义
mainApp.factory('myHttpInterceptor',function($q){
return {
'response' : function(_response){
if(_response.data.errorCode == 1){
console.info("myHttpInterceptor response:" + JSON.stringify(_response));
}
return _response;
}
}
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…