注入依赖于"运行"在Angularjs模块的方法 [英] Inject dependencies in "run" method of the module in Angularjs

查看:111
本文介绍了注入依赖于"运行"在Angularjs模块的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解我怎么用Angularjs工作。它看起来像漂亮的框架,但我还是坚持用DI一个小问题...

I trying to understand how do I work with Angularjs. It looks like nice framework, but I stuck with a little problem with 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 }; });  

为什么我需要它可能你问:)不过在我看来,首先关闭所有拥有有意义的命名空间来组织code。它也将最小化名称冲突并在上,minifing JS的时,事情发生故障,因为它命名为更缩短名称

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.

推荐答案

我认为,之所以

App.$inject = [CONFIGURATION, LOG_SERVICE];

行不通,是因为你还有其他2个参数$ rootScope与& $位置,你需要在$注射注入。所以它需要:

doesn't work, is because you have 2 other parameters "$rootScope" & "$location" that you need to inject in the $inject. So it needs to be:

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) {

}] );

这篇关于注入依赖于"运行"在Angularjs模块的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆