Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

Angular的Interceptor怎么配置到项目所有的module中?

  • 想针对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;
    }
  }
});
  • mainApp中定义的过滤器,并不适用于module1、module2子模块。该如何配置到所有的module中?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

谢邀。

所以可以明确一点,主 mainApp 定义的 $httpProvider 对你所依赖的其他子模块下同样适用

你的代码看起来没有什么任何问题,但我们项目中的确是不同模块中是相适用主模块的。唯一不同的好像在模块名上面。

像我们模块名都是这样的命名规则:

  • 主模块 ent

  • 业务模块 ent.user

类似这样,我不确定是不是这个原因!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...