【发布时间】:2016-10-18 02:16:17
【问题描述】:
我在玩angular services,发现我能够使用 Angular 服务,甚至无需注入它是 module。我创建了 3 个模块,即moduleA, moduleB, app。 moduleA 和 moduleB 相互独立,但 app 模块依赖于 moduleA 和 moduleB。这就是我创建模块的方式。
angular.module('moduleA',[]);
angular.module('moduleB',[]);
angular.module('app',['moduleA', 'moduleB']);
在moduleA 我有一个服务ServiceA 在moduleB 我有一个服务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 的package 或namespace。我们在模块中创建的任何内容都存在于该特定模块中。要获取该模块中定义的服务或特殊对象,我必须注入该模块。但不知道为什么我什至不注入就可以访问它。这是要玩的fiddle。
【问题讨论】:
标签: javascript angularjs dependency-injection