Angular将$ http注入配置或提供程序中

gwi*_*003 8 angularjs angular-routing angular-route-segment

我在我的角度应用程序中使用angular-route-segment并尝试从json feed配置段.

我已经有这个问题,因为我无法弄清楚如何注入$httpapp.config功能.这失败了Unknown provider: $http

myApp.config(["$http", "$routeSegmentProvider", function ($http, $routeSegmentProvider) {
   /* setup navigation here calling $routeSegmentProvider.when a number of times */
}
Run Code Online (Sandbox Code Playgroud)

因此,而不是注入$ HTTP到config,我也尝试注入$routeSegmentProvidermyApp.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 */
}]);
Run Code Online (Sandbox Code Playgroud)

我也试过了

myApp.run(["$http", "$routeSegmentProvider", function($http, $routeSegmentProvider)
Run Code Online (Sandbox Code Playgroud)

但我明白了 Unknown provider: $routeSegmentProviderProvider <- $routeSegmentProvider

cli*_*ers 12

提供者只能在"配置"阶段而不是"运行"阶段注入.相反,$ http等服务尚未在"配置"阶段初始化,只能在"运行"阶段使用.

解决这个问题的一个小技巧是在父函数范围中定义一个变量,以便"config"和"run"块都可以访问它:

var routeSegmentProvider = null;

myApp.config(["$routeSegmentProvider", function ($routeSegmentProvider) {
    routeSegmentProvider = $routeSegmentProvider;
}]);

myApp.run(["$http", function($http) {
  // access $http and routeSegmentProvider here
}]);
Run Code Online (Sandbox Code Playgroud)

我不确定你是否会遇到试图在运行阶段调用$ routeSegmentProvider.setup()的问题,因为我还没有尝试过.在过去,我能够使用相同的技术来注册依赖于某些自定义服务的http响应拦截器和$ httpProvider.

  • 虽然这可能不是最好的*解决方案,但它确实有用......我现在决定使用它.谢谢! (2认同)