如何注入角度拦截器

时间:2017-06-08 14:28:20

标签: javascript angularjs angular-http-interceptors

我意识到拦截器上有不少帖子,但我仍然很难让我去上班。在了解应该注入不同的东西时,我的角度知识是如此,等等。我相信代码是正确的,但我不确定如何将它注入到我的应用程序中。

我认为主要问题在于我如何在拦截器文件中使用angular.module('devtestApp')。我已经尝试将$ httpProvider.interceptors.push('JwtAuthInterceptor')移动到不同的位置但是没有任何反应,即没有使用拦截器,或者,当我有$ httpProvider.interceptors.push('JwtAuthInterceptor'时,我得到以下错误)在主app文件中取消注释。

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

INTERCEPTOR FILE:

 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');
});

MAIN APP FILE:

 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("!");

});

标题已记录服务器端(节点):

 { 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喜= treeForm:树:应用程序,           dnt:'1'}

很抱歉标题格式不正确,但这就是它们的全部内容。感谢您提供的任何帮助,如果您需要更多信息,请告诉我们!

1 个答案:

答案 0 :(得分:2)

你可以试试以下吗? ?这是我用于项目的结构。

创建自己的模块

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');
});

主要APP文件;添加新模块

 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("!");

});