使用Angular JS将常量注入其他模块配置

Inject constant to other modules config using Angular JS

本文关键字:其他 模块 配置 注入 常量 Angular JS 使用      更新时间:2023-09-26

我想在整个应用程序中共享一些变量,如基本路径。这些变量需要在模块配置期间可访问。我的观点是,我可以使用常量或提供者。

我有几个模块,每个模块都有自己的路由配置。在这些路由配置中,我想访问一些设置,例如。

这适用于应用程序模块配置,但不适用于其他模块配置(对于其他模块上的控制器),我总是得到"未知提供商:来自myApp.orders的信息"。

var myApp = angular.module('myApp', ['myApp.orders']);
myApp.constant('info', {
  version : '1.0'
});
myApp.config(function(info) {
  console.log('app config: ' + info.version);
});
myApp.controller('MyController', function (info) {
  console.log('controller: ' + info.version);
});
var orders = angular.module('myApp.orders', []);
// Remove comments to see it fail.
//orders.config(function(info) {
//  console.log('orders config: ' + info.version);
//});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <div ng-app="myApp" class="container" ng-controller="MyController">        
  </div>

我想我只是漏掉了一个小细节,你知道吗?

info常量在myApp模块中定义。如果我正确理解你的问题,你想使用其他模块中的常量(例如myApp.orders模块)。如果是这样的话,那么您需要将myApp注入myApp.orders,但看起来您想要做相反的操作。一种解决方案是将常量解耦到一个独立的模块中,并在需要时将其作为依赖项注入。

angular.module('constants', []) 
  .constant(...);
angular.module('myApp', ['constants', 'myApp.orders'])
  ...
angular.module('myApp.orders', ['constants'])
  ...

我不知道我的解决方案是否是最漂亮的,但我在index.html中放了一个CONFIG的定义,我从其他组件中引用了这个定义。我用服务器端代码生成了index.html,这样我就可以在程序启动时设置值。也就是说,我使用的是index.cshtml,但它和index.php或其他技术一样容易。以下是我的index.html:

....
 <script type="text/javascript">
    var usingMockDataGlobal = true;
 </script>
....

<script type="text/javascript">
        (function () {
            'use strict';
            var configData = {

                codeCampType: 'angu',
                loggedInUsername: 'peter',
                mockData: usingMockDataGlobal
            };
            angular.module('baseApp').constant('CONFIG', configData);

        })();
    </script>