Making a GET request in AngularJS's config
Making a GET request in AngularJS's config
这里有类似的问题,但在这种情况下似乎不起作用。我正在使用Angular-UI的谷歌地图API,它需要这样的配置:
.config(function(uiGmapGoogleMapApiProvider) {
uiGmapGoogleMapApiProvider.configure({
// key: 'your api key',
v: '3.20', //defaults to latest 3.X anyhow
libraries: 'weather,geometry,visualization'
});
})
我不想让我的API密钥直接在这里,我想通过GET请求('/api/googleAPI'
)使用路由从我的服务器加载它。然而,当我尝试时:
.config(function($http, uiGmapGoogleMapApiProvider) {
我得到:
Failed to instantiate module myApp due to: Error: [$injector:unpr] Unknown provider: $http
有什么解决办法吗?还是我应该厚颜无耻地把我的API密钥扔到这里?
基于@ryeballar的建议
在阅读了@ryeballer在评论中为我的另一个答案提供的链接后,有一个简单得多的解决方案,不需要您处理预引导处理或XMLHttpRequests
或上面非典型解决方案中建议的任何问题。
.config(function(uiGmapGoogleMapApiProvider) {
var $injector = angular.injector(['ng'])
var $http = $injector.get('$http')
$http.get(<url to your key>)
.then(function(rsp){
var data = rsp;
uiGmapGoogleMapApiProvider.configure({
key: data.key,
v: '3.20', //defaults to latest 3.X anyhow
libraries: 'weather,geometry,visualization'
})
})
})
我认为这可能是选择的答案,因为它很简单,而且它在典型的角度后引导生命周期内运行
有什么解决办法吗?还是我应该厚颜无耻地把我的API密钥扔到这里?
否请不要将API密钥放在其中,有解决方法。
在加载/注入/设置依赖关系时,angular有两个基本阶段。有配置阶段,然后是后配置 在config阶段,唯一可用于注入的是-Providers类型构造。这意味着您通常在服务或控制器中注入的任何东西都不能在您的配置函数中注入。 一旦您的应用程序已经启动、配置等,那么您就可以注入典型的可注入依赖项(例如$http、$q、$templateCache等) 因此,为了解决你的问题,我建议你如果不能利用 在我正在开发的应用程序中,我们也有类似的需求,需要通过.txt文件加载一些非角度配置数据。以下是我所做的: 首先推迟自动角度引导过程(这意味着我在主索引文件中省略了典型的 假设你的文本是一个简单的东西,比如一个键/值对,每对都在一个换行符上,你可以这样解析 然后引导Angular通过:配置阶段
配置后阶段
典型解决方案
module.run( function($http){ $http.get(<url to your config>) })
这样的东西那么您可能需要放弃使用CCD_ 4,并使用标准的CCD_。非典型溶液
ng-app
)。然后通过:加载.txt文件var client = new XMLHttpRequest();
client.open( 'GET', './version.txt' );
client.onload = function()
{
kickoffAngular(client.responseText)
}
client.send();
responseText
:kickoffAngular = function(text){
var kvPairs = text.split(''n')
kvPairs.forEach(function(kv){
var pair = kv.split('=')
var key = pair[0]
var val = pair[1]
... do something with them
})
}
angular.bootstrap( document, <app name> )
- 如何在angularJS中编辑时,如果DB中的值为true,则设置复选框,如果值为false,则取消选中复选框
- AngularJS:我可以跳过函数参数回调吗
- AngularJS UI路由器不能像ng路由器那样工作
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- 如何包含特定于每个视图angularjs的javascript文件
- AngularJs在app.config中的回调中配置路由
- config routeProvidar on angularJS
- AngularJS - 将提供程序注入模块.config
- AngularJS Provider 不会注入到 angular.config 中
- AngularJS - 如何在我自己的服务中使用.config()方法
- Making a GET request in AngularJS's config
- .config() of AngularJS
- Angularjs:在app.config中注入服务,使其不受缩小的影响
- Angularjs - 在module.config中动态添加值
- 在config()模块中注入依赖项-AngularJS
- Angularjs提供程序$get方法在config()上出错
- 如何在angularjs的app.config中注入依赖
- 如何在AngularJS中组织一些Utils文件以从app.config中调用
- AngularJS 'config'从一个模块到另一个模块
- 如果在angularJS的config中配置了stateProvider的状态,则在$state上返回null