如何注入 Angular 拦截器

How to Inject Angular Interceptor

我知道有很多关于拦截器的帖子,但我仍然很难让我的拦截器工作。我的 angular 知识是这样的,当涉及到理解不同的东西应该如何注入,在哪里等等。我相信代码是正确的,但我不确定如何将它注入我的应用程序。

我认为主要问题在于我如何在拦截器文件中使用 angular.module('devtestApp')。我尝试将 $httpProvider.interceptors.push('JwtAuthInterceptor') 移动到不同的位置,但要么没有任何反应,即未使用拦截器,要么,当我有 $httpProvider.interceptors.push('JwtAuthInterceptor') 在主应用程序文件中取消注释。

jquery.js:3869 未捕获错误:[$injector:unpr] 未知提供者:JwtAuthInterceptorProvider <- JwtAuthInterceptor <- $http <- $templateRequest <- $route

拦截器文件:

 angular.module('devtestApp')
  .factory('JwtAuthInterceptor', function ($localStorage, $q, $location) {

 return {
    request: function(config) {
      console.log('in the interceptor');
      config.headers.Authorization = 'Bearer ';
      config.headers = config.headers || {};
      if ($localStorage.getItem('token')) {
        // may also use sessionStorage
        config.headers.Authorization = 'Bearer ' + 
        $localStorage.getItem('token');
      }
      return config || $q.when(config);
    },
    response: function(response) {
      if (response.status === 401) {
        //  Redirect user to login page / signup Page.
        $location.path('/login');
      }
      return response || $q.when(response);
    }
  };
});

// Register the previously created JwtAuthInterceptor.
angular
  .module('devtestApp').config(function ($httpProvider) {
     $httpProvider.interceptors.push('JwtAuthInterceptor');
});

主应用程序文件:

 angular
  .module('devtestApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'angularSpinner',
'ngStorage'
  ])
  .config(function ($routeProvider, $locationProvider, $httpProvider, $qProvider) {
$routeProvider




  .when('/', {
    templateUrl: '/app/views/main.html',
    controller: 'MainCtrl',
    controllerAs: 'main'
  })
  ..... more of these

  // $httpProvider.interceptors.push('JwtAuthInterceptor');
  $locationProvider.html5Mode(false);
  $locationProvider.hashPrefix("!");

});

Headers 登录服务器端(节点):

 { host: 'localhost:8081',
  connection: 'keep-alive',
  pragma: 'no-cache',
  'cache-control': 'no-cache',
  accept: 'application/json, text/plain, */*',
  'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 
   (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
   referer: 'http://localhost:8081/',
   'accept-encoding': 'gzip, deflate, sdch, br',
    'accept-language': 'en-US,en;q=0.8',
    cookie: 'SQLiteManager_currentLangue=2; 

connect.sid=s%3AS4dpz1_ZhfwHFfVl9qBWnVKom8D4mgHh.04Kb%2B%2BsferIBZNavKQjRRoOvDwhFY7NjTjcabldEbio; JSESSIONID=d28168fff4793599a8c24f2f037c; treeForm_tree-hi=treeForm:tree:applications', dnt: '1' }

抱歉,headers 格式不正确,但这是完整的。感谢您提供的任何帮助,如果您需要更多信息,请告诉我!

你能试试下面的吗?? ?这是我在项目中使用的结构。

创建自己的模块

angular.module('myInterceptorModule')
  .factory('JwtAuthInterceptor', function ($localStorage, $q, $location) {

 return {
    request: function(config) {
      console.log('in the interceptor');
      config.headers.Authorization = 'Bearer ';
      config.headers = config.headers || {};
      if ($localStorage.getItem('token')) {
        // may also use sessionStorage
        config.headers.Authorization = 'Bearer ' + 
        $localStorage.getItem('token');
      }
      return config || $q.when(config);
    },
    response: function(response) {
      if (response.status === 401) {
        //  Redirect user to login page / signup Page.
        $location.path('/login');
      }
      return response || $q.when(response);
    }
  };
})

// Register the previously created JwtAuthInterceptor.
// I have removed the declaration of the module again; it is unecessary
.config(function ($httpProvider) {
     $httpProvider.interceptors.push('JwtAuthInterceptor');
});

主应用程序文件;添加新模块

 angular
  .module('devtestApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'angularSpinner',
'ngStorage',
'myInterceptorModule'
  ])
  .config(function ($routeProvider, $locationProvider, $httpProvider, $qProvider) {
$routeProvider
  .when('/', {
    templateUrl: '/app/views/main.html',
    controller: 'MainCtrl',
    controllerAs: 'main'
  })
  ..... more of these

  // $httpProvider.interceptors.push('JwtAuthInterceptor');
  $locationProvider.html5Mode(false);
  $locationProvider.hashPrefix("!");

});