【问题标题】:In Angular, why am I forced to declare the provider before the config?在 Angular 中,为什么我必须在配置之前声明提供程序?
【发布时间】:2015-12-08 10:37:35
【问题描述】:

为什么我必须在将使用它的config 函数之前声明provider

换句话说,这段代码有效:

angular.module('app')
  .provider('testService', function() {
    // ...
  })
  .config(function(testServiceProvider) {
    // ...
  });

但不是这个(得到了[$injector:unpr] Unknown provider: testServiceProvider):

angular.module('app')
  .config(function(testServiceProvider) {
    // ...
  })
  .provider('testService', function() {
    // ...
  });

(在我的真实代码中,这两个块是在单独的文件中定义的,因此加载这些文件的顺序非常重要)

我的理解是,当我调用 module('app').config(...)module('app').provider(...) 时,代码不会立即执行,而是在 Angular 应用程序启动时执行,因此,这就是 Angular 以正确顺序执行不同代码的作用(即provider 代码和然后 config 代码)。

谢谢

ps1:我已经看到this question了,其实是一样的,不过答案更多的是建议或者猜测……

ps2:我仍在使用 Angular 1.2,也许 Angular 1.3 - 1.4 改变了?

【问题讨论】:

    标签: angularjs angular-providers


    【解决方案1】:

    我已经在几个 Angular 版本上进行了测试,它似乎是 1.2.x 版本中的一个“错误”。从1.3.0版本开始,providerconfig的定义顺序不再重要。

    测试代码:

    angular.module('myApp',[])
      .provider('testService', function() {
        console.log('.. service');
        this.$get = function () {
          return {};
        };
      })
      .config(function(testServiceProvider) {
        console.log('.. config');
      });
    

    【讨论】:

      猜你喜欢
      • 2014-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-21
      • 1970-01-01
      • 2016-07-06
      • 2013-09-21
      相关资源
      最近更新 更多