【问题标题】:Why I am able to access angular service without injecting module?为什么我能够在不注入模块的情况下访问角度服务?
【发布时间】:2016-10-18 02:16:17
【问题描述】:

我在玩angular services,发现我能够使用 Angular 服务,甚至无需注入它是 module。我创建了 3 个模块,即moduleA, moduleB, appmoduleAmoduleB 相互独立,但 app 模块依赖于 moduleAmoduleB。这就是我创建模块的方式。

angular.module('moduleA',[]);
angular.module('moduleB',[]);
angular.module('app',['moduleA', 'moduleB']); 

moduleA 我有一个服务ServiceAmoduleB 我有一个服务ServiceB。这就是我定义服务的方式:

模块A

(function() {
  var app = angular.module('moduleA', []);
  app.service('ServiceA', function() {
    'use strict';
    this.greet = function() {
      alert('Greetings From Service A');
    };
  });
}());

moduleB 我已经在serviceB中注入了serviceA

(function() {
  'use strict';
  var app = angular.module('moduleB', []);
  app.service('ServiceB', function(ServiceA) {
    // I have not injected moduleA in moduleB but still
    // Don't know why I am able to access ServiceA
    // in ServiceB. Ideally I should not be able to access
    // anything which is defined in moudleA unlesss and until
    // I do not inject moduleA in moudleB.
    console.log(ServiceA);
    this.greet = function() {
      ServiceA.greet();
    };
  });
}());

最后 应用模块:

(function() {
  'use strict';
  var app = angular.module('app', ['moduleA', 'moduleB']);
  app.controller('MainController', ['$scope', 'ServiceA', 'ServiceB', function($scope, ServiceA, ServiceB) {
    $scope.greet = function() {
      ServiceB.greet();
    };
  }])
}());

现在担心的是我没有在moduleB 中注入moduleA,但我仍然可以在ServiceB 中的moduleB 中访问ServiceA 中的moduleA 我不知道为什么会这样。我从模块中了解到的是它们类似于 Java 或 Dot Net 的packagenamespace。我们在模块中创建的任何内容都存在于该特定模块中。要获取该模块中定义的服务或特殊对象,我必须注入该模块。但不知道为什么我什至不注入就可以访问它。这是要玩的fiddle

【问题讨论】:

    标签: javascript angularjs dependency-injection


    【解决方案1】:

    当一个模块被加载时,它的服务就可以被注入了。一旦在当前$injector 上定义了服务提供者,它就不会保存它属于哪个模块的信息。

    上面的代码是可行的,但它表明了一个坏习惯,因为如果没有加载moduleA,它将变得不可行。根据经验,模块应该加载它们所依赖的模块。可以在多个依赖模块中加载一个模块,它只会加载一次。

    config 块中的提供程序注入器使事情变得更加复杂(服务提供程序和服务实例有 two separate $injectors)。

    对于这个加载顺序

    angular.module('app',['moduleA', 'moduleB']); 
    

    这将按预期工作,因为在 config 块运行时已经定义了 ServiceA 服务提供者:

    angular.module('moduleB', []).config(function (ServiceAProvider) { ... });
    

    对于这个加载顺序

    angular.module('app',['moduleB', 'moduleA']); 
    

    会抛出注入器错误,因为config 块在app.service('ServiceA', ...) 定义ServiceAProvider 服务提供者之前运行。 app.service 方法可能比config 运行得更早,但是服务定义是排队的,不会立即生效。

    【讨论】:

    • 明白了。非常感谢:)
    【解决方案2】:

    如果在app中注入moduleA和moduleB,app中的所有模块都可以访问moduleA和moduleB的服务。这就是为什么您不需要在模块A 中注入模块B。这就是依赖项在 Angular 中的工作方式。

    如果您希望将 moduleA 仅注入到 moduleB 中(因为 mainController 中不需要它),您可以简单地从 app 模块中移除 moduleA 和 ServiceA,然后仅将它们注入到 moduleB 中。

    var app = angular.module('moduleB', ['moduleA']);
    

    请看这里fiddle

    【讨论】:

      猜你喜欢
      • 2018-05-11
      • 1970-01-01
      • 2018-07-18
      • 2014-09-03
      • 2019-03-07
      • 2017-05-09
      • 2010-10-16
      • 2022-07-28
      • 1970-01-01
      相关资源
      最近更新 更多