angularjs 在服务中包含另一个模块

angularjs include another module in a service

我想在我的服务中包含另一个模块,我有一些常量/配置相关。我的配置模块如下所示:

angular.module('myApp.config', [])
  .constant('EnvironmentConfig', {
    "WindowsAzureADConfig": {
      "tenant": "aaa.onmicrosoft.com", 
      "clientAppId": "xx-xx-xx-xx-xx", 
      "authority": "https://login.windows.net/aa.onmicrosoft.com", 
      "resourceUrl": "https://graph.windows.net/", 
      "redirectUrl": "http://localhost:4400/services/aad/redirectTarget.html"
    }, 
    "AppEndPointConfig": {
      "tokenAccess": "aa-aa-a-a-aa", 
      "baseURL": "http://aa.aaa.aa/api/", 
      "paths": {
        "bpath": "bpath/"
      }
    }, 
    "PConfig": {
      "ApiKey": "aaadd2dasdasdas23f44ffsfsdf", 
      "printerId": 244312
    }
  }
);

我有以下 angularjs 服务:

(function () {
  function MySrv(EnvironmentConfig) {
    var mySrv = {};
    var app = {
      aFunction: function () {
        console.log(EnvironmentConfig.authority); // getting undefined
      }
    };
    mySrv.app = app;

    return mySrv;
  }

  angular
    .module('myApp') // if adding .module('myApp', ['myApp.config']) then I'm getting a blank screen
    .service('MySrv', mySrv);
})();

请注意,模块是在服务本身之前包含和定义的。

你不能重新声明一个模块,当你

.module('myApp', ['myApp.config'])

因此,正如 Gustav 所说,您要么在第一次声明 myApp 的地方包含 myApp.config,要么将您的服务放在它自己的模块中,就像您对 myApp.config 所做的那样.

.module('myApp.service', ['myApp.config'])

但是您需要将服务模块包含到您的 myApp 模块中。像这样:

.module('myApp', ['myApp.service'])

由于服务模块包含配置模块,因此您无需将其包含在 myApp 模块中

权限在对象属性WindowsAzureADConfig中,所以需要更新日志方法。

参考下面带有模块依赖注入的工作代码片段

angular.module('myApp.config', [])
    .constant('EnvironmentConfig', {"WindowsAzureADConfig":{"tenant":"aaa.onmicrosoft.com","clientAppId":"xx-xx-xx-xx-xx","authority":"https://login.windows.net/aa.onmicrosoft.com","resourceUrl":"https://graph.windows.net/","redirectUrl":"http://localhost:4400/services/aad/redirectTarget.html"},"AppEndPointConfig":{"tokenAccess":"aa-aa-a-a-aa","baseURL":"http://aa.aaa.aa/api/","paths":{"bpath":"bpath/"}},"PConfig":{"ApiKey":"aaadd2dasdasdas23f44ffsfsdf","printerId":244312}});



(function() {

      function MySrv(EnvironmentConfig) {

        var mySrv = {};

        var app = {
        aFunction: function() {
          console.log(EnvironmentConfig.WindowsAzureADConfig.authority); // authority is inside the object property WindowsAzureADConfig, so you need to update the log method
        }
        };

        mySrv.app = app;

        return mySrv;
        }

    angular
    .module('myApp',['myApp.config']) // this is the way to add dependency in module
    .controller('myController', function($scope, MySrv){
        $scope.aFunction = function(){
            MySrv.app.aFunction();
        }
    })
    .service('MySrv',MySrv)
    

    })();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myController">
    <a ng-click="aFunction()">Click here</a>
</div>
</body>

希望对您有所帮助!