angular.js - How to configure Angular's Interceptor into all modules of the project?
为情所困
为情所困 2017-05-15 17:13:04
0
1
653
  • I want to uniformly handle Angular’s ​​$http request error codes (for example, when the user is not logged in, jump to the login page)

  • The cases on the Internet about $httpProvider interceptor are all configured in specific module.config (if there are many modules in the project, don’t you have to configure them one by one?)

  • Currently, my project code structure is that a JS file defines a module, and the main module depends on these sub-modules. Want to know how to configure $http error code interception processing to all modules?

//依赖的业务模块
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;
    }
  }
});
  • The filters defined in mainApp are not applicable to module1 and module2 sub-modules. How to configure it in all modules?

为情所困
为情所困

reply all(1)
黄舟

Thanks for the invitation.

So it’s clear that the main mainApp 定义的 $httpProvider also applies to other submodules that you depend on.

There doesn’t seem to be any problem with your code, but in our project it is true that different modules use the same main module. The only difference seems to be the module name.

Our module names all follow this naming rule:

  • Main module

    . ent

  • Business Module

    . ent.user

Similar to this, I’m not sure if this is the reason!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template