无法从服务访问应用程序的常量

时间:2016-04-16 07:43:18

标签: angularjs

我需要在myService.js访问常量' appSettings'来自app.js?

app.js

(function () {
    'use strict';
    angular
        .module('myApp', ['ngMaterial'])
        .constant('appSettings', {
            someValue: 123
        })
})();

这是我的服务/ myService.js

(function () {
    'use strict';
    angular
        .module('myApp')
        .factory('myService', ['appSettings', MyService]);

    function MyService(appSettings) {
        console.log(appSettings.someValue)
    }
})();

浏览器的控制台说appSettings.someValue未定义。

1 个答案:

答案 0 :(得分:1)

不确定您遇到的问题是什么,但我可以访问该值。



(function() {
  'use strict';
  angular
    .module('myApp', [])
    .constant('appSettings', {
      someValue: 123
    })
})();

(function() {
  'use strict';
  angular
    .module('myApp')
    .factory('myService', ['appSettings', MyService]);

  function MyService(appSettings) {
    console.log(appSettings.someValue);
    alert(appSettings.someValue);
    
    return {
      foo: function() {}
    }
  }

  angular.module("myApp")
    .controller("sa", function($scope, myService) {
      myService.foo();
    })
})();

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="sa"></div>
&#13;
&#13;
&#13;