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

六眼飞鱼酱① 提交于 2019-12-14 02:18:02

问题


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?


回答1:


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

function ServiceOne($http, NAME1) {

   var service = {...
   ...

 }

here is a good explanation




回答2:


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



回答3:


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

}


来源:https://stackoverflow.com/questions/30220201/how-to-inject-module-and-make-it-accesible-to-entrie-angular-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!