2015-05-13 79 views
2

我有一個模塊(app.config),我想注入我的整個應用程序。如何注入模塊,並使其訪問角應用程序

模塊需要被注入到應用

舉例而言,所有其它模塊中訪問,我的應用程序是這樣的:

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

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

這裏的app.config

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

我想'app.config'注入的方式可以在所有模塊(模塊#1,模塊#2,....)內部訪問。

這裏是我的問題:

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

function ServiceOne($http) { 

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

    return service; 
} 

問題 - >NAME1是不確定的。但我想我注入到整個應用程序?

我不想單獨將app.config注入到每個模塊。任何其他解決方案?

回答

3

您需要將常量注入到控制器中。

function ServiceOne($http, NAME1) { 

    var service = {... 
    ... 

} 

這裏是一個很好的explanation

0

NAME1是由角知道注入恆定的關鍵,但你永遠不注入了!此外,您需要在'Module1'中添加對設置常量的模塊(在本例中爲'app.config')的依賴關係。另外,當我創建服務時,我只是將方法添加到this這是對服務本身的引用,所以我不需要費心爲服務創建對象並像在示例中那樣返回它。最後,最好的做法是使用inline array annotation for dependency injection,如下面的示例所示。嘗試了這一點:

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

} 
0

,你可以設置一個配置對象

的app.config

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

然後

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; 
} 
相關問題