将http注入AngularJS中的httpProvider

时间:2015-06-24 20:36:28

标签: angularjs

我希望通过让客户端终止会话来自动注销用户(而不是让会话自行消亡)。我将一个拦截器推到$ httpProvider上,这允许我设置和重置超时计时器,但问题是我无法弄清楚如何调用需要$ http的注销功能。这总是产生循环依赖。有没有办法做到这一点?

app.config(['$httpProvider', function($httpProvider) {
  $httpProvider.interceptors.push(
    function() {
      return {
        response: function(response) { $http({ ... }); }
      })}

如果我使$ http成为一个依赖项,我得到一个循环依赖项,但是没有$ http依赖项,对$ http的调用显然不起作用。

3 个答案:

答案 0 :(得分:2)

你应该小心在拦截器中使用$ http,因为它有可能导致无限循环。考虑重构,所以$ http不是必需的

那说你可以尝试注入$ injector。然后,您要在哪里制作$ http请求,只需使用$injector.get('$http')

app.config(['$httpProvider, $injector', function($httpProvider, $injector) {
  $httpProvider.interceptors.push(
    function() {
      return {
        response: function(response) { $injector.get('$http') }
      })}

答案 1 :(得分:1)

您需要在$http函数中注入inceptor.push依赖性,您还可以从那里注入其他依赖项。

<强>代码

app.config(['$httpProvider',
    function($httpProvider) {
       $httpProvider.interceptors.push(
         function($http) { //<--here you could make dependency available.
           return {
             response: function(response) {
               $http({...});
             }
           })
         }])

答案 2 :(得分:0)

我使用了先前答案的交叉点(使用$ injector,但在push()中)以使其按预期工作:

app.config(['$httpProvider', function($httpProvider) {

  $httpProvider.interceptors.push(function($q, $injector) {
      ...
      //now get $http like this and use it as needed:
      $injector.get('$http')