Javascript 在 Angularjs 模块的“run”方法中注入依赖
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14688290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inject dependencies in "run" method of the module in Angularjs
提问by Alex Dn
I trying to understand how do I work with Angularjs. It looks like nice framework, but I stuck with a little problem with DI...
我试图了解我如何使用 Angularjs。它看起来像一个不错的框架,但我在 DI 方面遇到了一个小问题......
How I can inject dependecies in "run" method of the module? I mean I able to do it, but it works only if I have service/factory/value with as same name as "run" parameter name. I build a simple application do illustrate what I mean:
如何在模块的“运行”方法中注入依赖项?我的意思是我可以做到,但只有当我的服务/工厂/值与“运行”参数名称同名时才有效。我构建了一个简单的应用程序来说明我的意思:
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 }; });
Why I need it may you ask :) But in my mind, first off all to have meaningful namespaces to organize the code. It will also minimize name collision and in the last, when minifing the JS, the things breaks down, since it renamed to more shorten names.
为什么我需要它,你可能会问:) 但在我看来,首先要有有意义的命名空间来组织代码。它还将最大限度地减少名称冲突,最后,在缩小 JS 时,事情会崩溃,因为它重命名为更短的名称。
回答by Shai Reznik - HiRez.io
I think that the reason
我认为原因
App.$inject = [CONFIGURATION, LOG_SERVICE];
doesn't work, is because you have 2 other parameters $rootScope& $locationthat you need to inject in the $inject. So it needs to be:
不起作用,是因为您还有 2 个其他参数$rootScope,$location并且需要在$inject. 所以它需要是:
App.$inject = ["$rootScope", "$location", CONFIGURATION, LOG_SERVICE];
Another way you can inject your service is to use this version:
注入服务的另一种方法是使用此版本:
app.run(["$rootScope", "$location", CONFIGURATION, LOG_SERVICE,
function ($rootScope, $location, Configuration, LogService) {
}] );

