我对 AngularJS 框架相当陌生,但基本上我想做的是将 CSRF token 注入(inject)我的应用程序,但我想根据配置更改 url。这是我目前所拥有的:
var VERISION_API = 'v1';
var config_data = {
'CFG': {
'EP': 'https://mydomain.com/api/' + VERISION_API + '/web/'
}
};
var configMod = angular.module("cfg",[]);
angular.forEach(config_data,function(key,value) {
configMod.constant(value,key);
});
var myApp = angular.module("app", ["cfg", "ngResource", "ngRoute"]);
(function () {
var $injector = angular.injector(['ng']);
$injector.invoke(['cfg', '$http', '$rootScope', function (cfg, $http, $rootScope) {
$rootScope.$apply(function (CFG) {
$http.get(CFG.EP + "accounts/csrf").then(function (response) {
myApp.constant("CSRF_TOKEN", response.csrf_token);
angular.bootstrap(document, ['app']);
});
});
}]);
})();
我不断收到以下错误:
Uncaught Error :[$injector:unpr] 未知提供者:cfgProvider <- cfg
我知道这与我运行 $injector.invoke 的方式有关,但我已经尝试了所有方法。希望有人能帮助我并告诉我我做错了什么?
最佳答案
几个问题,请参见内联:-
var $injector = angular.injector(['ng', 'cfg']); //<-- Add module name here
/*Injection is case sensitive it mustbe CFG*/
$injector.invoke(['CFG', '$http', '$rootScope', function (cfg, $http, $rootScope) {
$rootScope.$apply(function () { //Do not set an argument here
$http.get(cfg.EP + "accounts/csrf").then(function (response) {
myApp.constant("CSRF_TOKEN", response.csrf_token);
angular.bootstrap(document, ['app']);
});
});
}]);
1)你需要获取带有依赖的模块的注入(inject)器,例如:
var $injector = angular.injector(['ng', 'cfg']);
2) DI service/provider/etc.. 名称区分大小写,因此:
$injector.invoke(['CFG',...
3) 不要在$rootScope.$apply
的匿名函数中传递参数,它将在该范围内创建一个局部变量。所以只是:
$rootScope.$apply(function () {
注入(inject)的依赖项可作为上层范围的变量(参数 cfg
)使用,因此只需按以下方式访问它:
$http.get(cfg.EP + "accounts/csrf");
检查演示中的网络控制台:
var configMod = angular.module("cfg", []);
var config_data = {
'CFG': {
'EP': 'https://mydomain.com/api//web/'
}
};
var configMod = angular.module("cfg", []);
angular.forEach(config_data, function(key, value) {
configMod.constant(value, key);
});
var myApp = angular.module("app", ["cfg", "ngResource", "ngRoute"]);
(function() {
var $injector = angular.injector(['ng', 'cfg']); //<-- Add module name here
/*Injection is case sensitive it mustbe CFG*/
$injector.invoke(['CFG', '$http', '$rootScope',
function(cfg, $http, $rootScope) {
$rootScope.$apply(function() { //Do not set an argument here
$http.get(cfg.EP + "accounts/csrf").then(function(response) {
myApp.constant("CSRF_TOKEN", response.csrf_token);
angular.bootstrap(document, ['app']);
});
});
}
]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
关于javascript - 找不到 AngularJS 配置模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27803340/