在Angularjs中的模块的"run"方法中注入依赖项

Ale*_* Dn 50 javascript angularjs

我试图了解如何使用Angularjs.它看起来很漂亮的框架,但我坚持DI的一个小问题...

如何在模块的"run"方法中注入dependecies?我的意思是我能够做到这一点,但只有当我的服务/工厂/值与"运行"参数名称同名时才有效.我构建一个简单的应用程序来说明我的意思:

var CONFIGURATION = "Configuration"; //I would like to have App.Configuration
var LOG_SERVICE = "LogService"; //I would like to have App.Services.LogService
var LOGIN_CONTROLLER = "LoginController";

var App = {};
App.Services = {};
App.Controllers = {};

App = angular.extend(App, angular.module("App", [])
            .run(function ($rootScope, $location, Configuration, LogService) {

                //How to force LogService to be the logger in params?
                //not var = logger = LogService :)
                LogService.log("app run");
            }));
//App.$inject = [CONFIGURATION, LOG_SERVICE]; /* NOT WORKS */

App.Services.LogService = function (config) {
    this.log = function (message) { 
                   config.hasConsole ? console.log(message) : alert(message); 
               };
};
App.Services.LogService.$inject = [CONFIGURATION];
App.service(LOG_SERVICE, App.Services.LogService);

App.Controllers.LoginController = function (config, logger) {
    logger.log("Controller constructed");
}
//The line below, required only because of problem described
App.Controllers.LoginController.$inject = [CONFIGURATION, LOG_SERVICE];

App.factory(CONFIGURATION, function () { return { hasConsole: console && console.log }; });  
Run Code Online (Sandbox Code Playgroud)

为什么我需要它可能你会问:)但在我看来,首先要有一个有意义的命名空间来组织代码.它还可以最大限度地减少名称冲突,最后,当迷你JS时,事情就会崩溃,因为它重命名为更短的名字.

Sha*_*.io 85

我认为原因

App.$inject = [CONFIGURATION, LOG_SERVICE];
Run Code Online (Sandbox Code Playgroud)

不工作,是因为你有其他2个参数$rootScope$location您需要的注入$inject.所以它需要是:

App.$inject = ["$rootScope", "$location", CONFIGURATION, LOG_SERVICE];
Run Code Online (Sandbox Code Playgroud)

注入服务的另一种方法是使用此版本:

app.run(["$rootScope", "$location", CONFIGURATION, LOG_SERVICE, 
         function ($rootScope, $location, Configuration, LogService) {

}] );
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,传递数组运行找到了工作!! (4认同)
  • 是的,如果代码被缩小,则需要在执行依赖注入时传递数组(因为变量名称$ rootScope和$ location可能会因缩小为a和b而改变). (2认同)