Angular 将 $http 注入配置或提供程序以运行 [英] Angular Inject $http into config or provider into run
问题描述
我在我的 angular 应用程序中使用 angular-route-segment 并尝试从 json 提要配置段.
I am using angular-route-segment in my angular app and an trying to configure the segments from a json feed.
我遇到了这个问题,因为我不知道如何将 $http
注入到 app.config
函数中.这失败了 Unknown provider: $http
I have having problems with this, because I can't figure out how to inject $http
into the app.config
function. This fails with Unknown provider: $http
myApp.config(["$http", "$routeSegmentProvider", function ($http, $routeSegmentProvider) {
/* setup navigation here calling $routeSegmentProvider.when a number of times */
}
因此,我没有将 $http 注入 config
,而是尝试将 $routeSegmentProvider
注入 myApp.run
So instead of injecting $http into config
, I also tried injecting $routeSegmentProvider
into myApp.run
myApp.run(["$http", "$routeSegment", function($http, $routeSegment) {
/* can use $http here to get data, but $routeSegment is not the same here */
/* $routeSegment does not have the when setup method */
}]);
我也试过
myApp.run(["$http", "$routeSegmentProvider", function($http, $routeSegmentProvider)
但我得到 Unknown provider: $routeSegmentProviderProvider <- $routeSegmentProvider
推荐答案
Providers 只能在config"阶段被注入,而不能在run"阶段被注入.相反,像 $http 这样的服务在config"阶段还没有初始化,只会在run"阶段可用.
Providers can only be injected in the "config" phase and not the "run" phase. Conversely, a service such as $http will not have been initialized yet in the "config" phase and will only be available in the "run" phase.
解决这个问题的一个小技巧是在父函数作用域中定义一个变量,以便config"和run"块都可以访问它:
A little trick to work around this is to define a variable in the parent function scope so that both the "config" and "run" blocks can have access to it:
var routeSegmentProvider = null;
myApp.config(["$routeSegmentProvider", function ($routeSegmentProvider) {
routeSegmentProvider = $routeSegmentProvider;
}]);
myApp.run(["$http", function($http) {
// access $http and routeSegmentProvider here
}]);
我不确定在运行阶段尝试调用 $routeSegmentProvider.setup() 是否会遇到问题,因为我没有尝试过.过去,我能够使用相同的技术来注册依赖于 $httpProvider 的某些自定义服务的 http 响应拦截器.
I'm not sure if you will encounter problems trying to call $routeSegmentProvider.setup() within the run phase as I haven't tried. In the past I was able to use the same technique to register http response interceptors that depend on some custom services with the $httpProvider.
这篇关于Angular 将 $http 注入配置或提供程序以运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!