总之装饰可被描述为如下: -
装饰器功能截取服务的创建,允许它 重写或修改服务的行为。
它通过角使用$provide
服务和修改或替换另一个服务的实现
$provide.decorator('service to decorate',['$delegate', function($delegate) {
// $delegate - The original service instance,
// which can be replaced, monkey patched,
// configured, decorated or delegated to.
// ie here what is there in the 'service to decorate'
// This function will be invoked,
// when the service needs to be provided
// and should return the decorated service instance.
return $delegate;
}]);
实施例:
$provide.decorator('$log', ['$delegate', function($delegate) {
// This will change implementation of log.war to log.error
$delegate.warn = $delegate.error;
return $delegate;
}]);
应用
除了@JBland答案。
很好的例子。我真的想知道如何扩展第三方模块的功能而不用插手他们 – 2014-01-29 14:30:03
装饰者是否实际上鸭子服务的所有实例,还是仅限于装饰它们的模块?换句话说,假设我有模块A来装饰模块B的服务。然后我有模块C,它依赖于模块A和模块B.在模块C内部,模块B的服务是原始还是装饰版本? – 2014-02-26 23:32:22
@JonJaques - 这是一个很好的问题。我没有遇到过这种情况。如果我猜测,模块C所看到的服务版本应该是模块A中的服务版本,但我不能肯定地说,直到我自己尝试。你为什么不写一个简单的plunkr/jsffidle并对其进行实验。如果你能和我们分享你的发现,那将是非常棒的。干杯。 – tamakisquare 2014-02-28 22:32:02