一尘不染

在Angularjs中的模块的“运行”方法中注入依赖项

angularjs

我试图了解如何使用Angularjs。看起来不错的框架,但是我在DI方面遇到了一些问题…

如何在模块的“运行”方法中注入依赖项?我的意思是我能够做到,但是仅当我具有与“运行”参数名称相同名称的服务/工厂/值时,它才有效。我构建了一个简单的应用程序来说明我的意思:

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 }; });

您可能会问我为什么需要它:)但是,在我看来,首先要有有意义的名称空间来组织代码。它还将最小化名称冲突,最后,当最小化JS时,由于将其重命名为更短的名称,因此情况会恶化。


阅读 241

收藏
2020-07-04

共1个答案

一尘不染

我认为原因

App.$inject = [CONFIGURATION, LOG_SERVICE];

之所以不起作用,是因为您还有其他2个参数$rootScope$location并且需要在中插入$inject。因此它必须是:

App.$inject = ["$rootScope", "$location", CONFIGURATION, LOG_SERVICE];

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

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

}] );
2020-07-04