【问题标题】:Injecting factories into config blocks将工厂注入配置块
【发布时间】:2013-08-30 19:57:10
【问题描述】:

我无法弄清楚这一点。目前正在深入研究更多injection 文档,但我不确定为什么这不起作用。在下面的示例中,myConstants.defaultPath 记录为 undefined

(function() {
  angular.module('my-constants', []).factory('myConstants', [
    function() {
      var service;
      return service = {
        defaultPath: '/aroute'
      };
    }
  ]);

}).call(this);


(function() {
  var app, config;

  app = angular.module('my-app', ["my-constants"]);

  config = function($routeProvider, $httpProvider, myConstants) {

    console.log(myConstants.defaultPath); // undefined

    return $routeProvider.otherwise({
      redirectTo: myConstants.defaultPath
    });
  };

  config.$inject = ['$routeProvider', '$httpProvider', 'myConstantsProvider'];

  app.config(config);

}).call(this);

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    我建议你用module.constant注册常量,它可以在config和任何其他方法中使用。

    angular.module('my-constants', []).constant('myConstants', {
      defaultPath: '/aroute'
    })
    

    注入配置(注意:myConstants 不是 myConstantsProvider):

    config.$inject = ['$routeProvider', '$httpProvider', 'myConstants'];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      • 2016-02-18
      • 1970-01-01
      相关资源
      最近更新 更多