角注入$ HTTP到配置或提供者进入运行 [英] Angular Inject $http into config or provider into run

查看:233
本文介绍了角注入$ HTTP到配置或提供者进入运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的角度路由段在我的角度应用程序和一个试图从一个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 功能。这将失败,未知提供商:$ 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到配置,我也试过注射 $ routeSegmentProvider 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)`

但我得到未知提供商:$ routeSegmentProviderProvider< - $ routeSegmentProvider

推荐答案

供应商只能在配置阶段,而不是跑阶段注入。相反,如$ HTTP服务将还没有被在配置阶段初始化,并且只会在运行阶段是可用的。

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.

一个小窍门来解决,这是定义在父函数范围的变量,这样无论是配置和运行块可以访问它:

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(),因为我还没有尝试过的问题。在过去,我能够用同样的方法来注册依赖于一些定制服务,HTTP响应拦截器$ httpProvider。

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.

这篇关于角注入$ HTTP到配置或提供者进入运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆