raneshu
raneshu

Reputation: 413

How to inject module and make it accesible to entrie angular app

I have a module (app.config) that I would like to inject my entire app.

The module needs to be accessible within all other modules injected into the app

For example, my app looks like this:

angular.module('myApp', [
    'app.config',
    'module#1',
    'module#2',
    'module#3',
    'module#4'    
])
.config...

/////////////////////////////////

Here's app.config

angular.module('app.config', []).
    constant('NAME1', 'Name1').
    constant('NAME2', 'Name2'); 
////////////////////

I want 'app.config' injected in such a way that it can be accessed inside all modules (module#1','module#2',....) as well.

Here's my problem:

angular.module('module#1', []).
    service('serviceOne', serviceOne);

function ServiceOne($http) {

    var service = {
        getMyProfile: function(){return $http.get('api/' + NAME1);}
    };

    return service;
}

Problem -> NAME1 is undefined. But I thought I injected it to the entire app???

I don't want to individually inject app.config to each module. Any other solutions?

Upvotes: 2

Views: 97

Answers (3)

hartz89
hartz89

Reputation: 669

NAME1 is the key by which Angular knows to inject the constant, but you never injected it! Also, you need to add a dependency on the module in which you set the constants (in this case, 'app.config') in 'Module1'. Also, when I'm creating services, I just add the methods to this which is a reference to the service itself, so I don't need to bother with creating an object for the service and returning it as you were doing in your example. Finally, it's best practice to use the inline array annotation for dependency injection as shown in my example below. Try this out:

var mod1 = angular.module('Module1', ['app.config']);

mod1.service('ServiceOne', ['$http', 'NAME1', serviceOne]);

function ServiceOne($http, NAME1) {

  this.getMyProfile = function() {
    return $http.get('api/' + NAME1);
  };

}

Upvotes: 0

Robert
Robert

Reputation: 677

You could setup a config object

app.config

module.exports = {
    NAME1: 'Name1',
    NAME2: 'Name2'
}

and then

var config = require('../config');

angular.module('module#1', []).
    service('serviceOne', serviceOne);

function ServiceOne($http) {

    var service = {
        getMyProfile: function(){return $http.get('api/' + config.NAME1);}
    };

    return service;
}

Upvotes: 0

Kalhan.Toress
Kalhan.Toress

Reputation: 21911

you need to inject the constants in to the controller as well.

function ServiceOne($http, NAME1) {

   var service = {...
   ...

 }

here is a good explanation

Upvotes: 3

Related Questions