【发布时间】:2013-05-19 20:34:25
【问题描述】:
我对 angularjs 应用程序的工作原理有点困惑。
首先我应该说我是一个新手 angularjs 用户,但我熟悉其他语言的其他 DI 框架(如 PHP 中的 symfony,Java 中的 spring,有点 Unity)。
这些 DI 实现中的每一个都需要类定义和 DI 配置。
配置通常包括:
- 如何应该是类注入(自动按名称或类型,或手动)
- 如果容器应该返回一个单例实例
- 应该使用什么工厂类来创建对象
- serviceIds - 可以通过 serviceId 检索每个服务。这个 serviceId 表示创建实例的配置(应该注入哪些服务以及应该使用哪些参数)。
- 等
而我在 angularjs 中缺少的这个配置。
有一个 dumb example 我期望这样的配置应该如何工作。我有两个服务,每个都做类似的事情,但有不同的实现。
angular.module('notify', [], function($provide) {
$provide.factory('LogNotifier', function($window) {
return {
messageMe: function(message) {
$window.console.log(message);
}
}
});
$provide.factory('AlertNotifier', function($window) {
return {
messageMe: function(message) {
$window.alert(message);
}
}
});
});
angular.module('myModule', ['notify'], function($provide) {
// as notifier dependency I must specify its type.
// is there any way how I would configure after its definition
// which notifier implementation should be used?
$provide.factory('DataLoader', function(AlertNotifier) {
var loader = {
loadAllItems: function() {
AlertNotifier.messageMe('Loading items');
// let's asume there is ajax call and promise object return
return [
{name: 'Item1'},
{name: 'Item2'}
];
}
}
return loader;
});
});
我想在 LogNotifier 和 AlertNotifier 之间切换而不更改 DataLoader 服务的源代码。这可能吗?
谢谢
【问题讨论】:
标签: javascript configuration angularjs dependency-injection