【问题标题】:How to Inject Angular Interceptor如何注入 Angular 拦截器
【发布时间】:2017-06-09 03:05:40
【问题描述】:

我意识到有很多关于拦截器的帖子,但我仍然很难让我的工作。我的角度知识是如此之多,因此在了解应该如何注入不同的东西,在哪里等方面。我相信代码是正确的,但我不确定如何将其注入我的应用程序中。

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

jquery.js:3869 未捕获错误:[$injector:unpr] 未知提供者:JwtAuthInterceptorProvider

拦截器文件:

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

});

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

 { 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' }

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

【问题讨论】:

  • 似乎您的拦截器和推送定义明确。您能否添加该调用的 http 调用 + 请求标头,以查看是否没有像您一样调用拦截器:config.headers.Authorization = 'Bearer';
  • 我不确定这是否对您所看到的行为有任何影响,但您应该能够消除 return 语句的左侧并始终返回 $q.when包装的配置或响应。
  • @aorfevre 我用服务器端显示的标题更新了帖子。他们不在那里 :(。我是否必须手动将任何内容添加到我的服务文件中(所有 http.get/post/put 都是从其中调用的)?
  • 否;这是拦截器执行这些自动操作的目标;)因此;使用拦截器时,您不应在 $http 调用中添加特定参数/设置
  • @aorfevre 你认为错误在于我如何在拦截器文件中调用 angular .module('devtestApp') 吗?我应该在那个文件中处理这个问题吗?

标签: javascript angularjs angular-http-interceptors


【解决方案1】:

您可以尝试以下方法吗? ?这是我用于项目的结构。

创建自己的模块

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

});

【讨论】:

  • 这成功了!非常感谢您的帮助,非常感谢。
猜你喜欢
  • 2020-06-03
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
  • 2018-05-17
  • 2023-03-13
  • 2014-02-09
  • 2018-07-08
  • 2021-07-13
相关资源
最近更新 更多