angular.js - Angular的Interceptor怎么配置到项目所有的module中?

浏览:64日期:2022-12-21

问题描述

想针对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中?

问题解答

回答1:

谢邀。

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

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

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

主模块 ent。

业务模块 ent.user。

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

相关文章: