【问题标题】:Is there a way to request $http for an interceptor?有没有办法为拦截器请求 $http ?
【发布时间】:2014-01-14 16:45:38
【问题描述】:

这个想法是在某些情况下从另一个来源获取数据,所以我有这个存根:

factory("interceptor", function ($q, $location, $http) {
    return function (promise) {
        return promise;
    }
}

失败了

[$injector:cdep] 找到循环依赖:拦截器

还尝试注入 $injector 并使用它检索 $http,结果相同。有什么想法吗?

.config 只不过是声明:

.config(function ($httpProvider) {
    $httpProvider.responseInterceptors.push('interceptor');
});

【问题讨论】:

  • @IlanFrumer 是的,感谢您的有用评论。
  • 为什么要在拦截器中注入$http?
  • 如问题所述:从另一个来源获取数据。例如。最需要的是 /url/one.js,我想用 /url/two.js 中的数据替换它。

标签: angularjs


【解决方案1】:

$injector 注入interceptor

使用它在回调函数的返回对象中获取$http

这是example

app.config(function ($httpProvider) {
  $httpProvider.interceptors.push('interceptor');
});

app.factory("interceptor", function ($q, $location, $injector) {
  return {
    request: function(config){      
      var $http = $injector.get('$http');
      console.dir($http);
      return config;
    }
  }
});

app.run(function($http){
  $http.get('/')
});

【讨论】:

  • 我可以使用这个在拦截器中发出 $http 请求吗?我需要这样做
【解决方案2】:

在查看 Angular 源代码后,更好的答案是这样的。 $http 方法无需依赖注入即可访问,因此诀窍是不注入 $http 并简单地使用它。像这样:

Right Way

retryModule = angular.module('retry-call', [])

# Do not inject $http
retryModule.factory 'RetryCall', ($q)->
  # More object keys
  'responseError': (response)=>
    # Just use $http without injecting it
    $http(response.config)
    $q.reject(response)

retryModule.config ['$httpProvider', ($httpProvider)->
    $httpProvider.interceptors.push('RetryCall');
]

Wrong Way

# Do not do it this way.
retryModule.factory 'RetryCall', ($q,$http)->

【讨论】:

  • 这是一个很高的要求,但看起来很整洁。如果没有从$injector 获得它,我无法在我的拦截器中使用$http,但我可能误解了你的观点。有没有可能你有一个小提琴或者可以指出你从源头那里学到的?
猜你喜欢
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多