AngularJS 找不到配置模块

AngularJS configuration module not being found

我是 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 的方式有关,但我已经尝试了所有方法。希望有人能帮助我并告诉我我做错了什么?

angular 通过精确区分大小写的字符串键从 providerCache 获取服务,因此应使用 CFG

几个问题,见内联:-

  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 service/provider/etc.. 名称区分大小写,因此:

  $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>