我对AngularJS框架相当陌生,但基本上我要做的是向我的应用程序中注入一个CSRF令牌,但我想根据配置更改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']);
});
});
}]);
})();我一直收到以下错误:
未知错误:$injector:unpr未知提供者: cfgProvider <- cfg
我知道这与我运行$injector.invoke的方式有关,但我已经尝试了一切。希望有人能帮我,告诉我我做错了什么?
发布于 2015-01-06 16:57:47
几个问题,见内联:-
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)您需要获得具有依赖项的模块的注入器,例如:
var $injector = angular.injector(['ng', 'cfg']);( 2) DI服务/提供者/等等。名称区分大小写,因此:
$injector.invoke(['CFG',...3)不要在$rootScope.$apply的匿名函数中传递参数,它将在该范围内创建一个局部变量。所以只要:
$rootScope.$apply(function () {注入的依赖关系可以作为变量(参数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>
发布于 2015-01-06 16:56:35
通过严格区分字符串键大小写从providerCache获得服务,因此应该使用CFG
https://stackoverflow.com/questions/27803340
复制相似问题