在angularJS

时间:2015-12-07 09:17:55

标签: angularjs dependency-injection decorator angular-decorator

使用angularJS时,您可以使用$provide.decorator('thatService',decoratorFn)为服务注册装饰功能。

创建服务实例后,$injector会将它(服务实例)传递给已注册的装饰功能,并将该功能的结果用作装饰服务。

现在假设thatService使用已注入其中的thatOtherService

如何获取对thatOtherService的引用,以便我能够在我的decoratorFN要添加到.myNewMethodForThatService()的{​​{1}}中使用它?

1 个答案:

答案 0 :(得分:4)

这取决于确切的用例 - 确定答案需要更多信息 (除非我误解了要求),这里有两种选择:

1)展开ThatOtherService的{​​{1}}:

ThatService

2)在装饰器函数中注入.service('ThatService', function ThatServiceService($log, ThatOtherService) { this._somethingElseDoer = ThatOtherService; this.doSomething = function doSomething() { $log.log('[SERVICE-1]: Doing something first...'); ThatOtherService.doSomethingElse(); }; }) .config(function configProvide($provide) { $provide.decorator('ThatService', function decorateThatService($delegate, $log) { // Let's add a new method to `ThatService` $delegate.doSomethingNew = function doSomethingNew() { $log.log('[SERVICE-1]: Let\'s try something new...'); // We still need to do something else afterwards, so let's use // `ThatService`'s dependency (which is exposed as `_somethingElseDoer`) $delegate._somethingElseDoer.doSomethingElse(); }; return $delegate; }); });

ThatOtherService

您可以在此demo中查看两种方法。