總之裝飾可被描述爲如下: -
裝飾器功能截取服務的創建,允許它 重寫或修改服務的行爲。
它通過角使用$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