Inject dependencies in "run" method of the module in Angularjs

JavascriptAngularjs

Javascript Problem Overview


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

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.

Javascript Solutions


Solution 1 - Javascript

I think that the reason

App.$inject = [CONFIGURATION, LOG_SERVICE];

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

}] );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex DnView Question on Stackoverflow
Solution 1 - JavascriptShai Reznik - HiRez.ioView Answer on Stackoverflow