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

创建服务实例后,$injector会将其(服务实例)传递给已注册的修饰函数,并将该函数的结果用作修饰的服务。

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

如何获得对thatOtherService的引用,以便可以在我的decoratorFN想要添加到.myNewMethodForThatService()thatService中使用它?

最佳答案

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

1)从ThatOtherService公开ThatService

.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;
  });
});


2)在装饰器函数中注入ThatOtherService

.service('ThatService', function ThatServiceService($log, 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, ThatOtherService) {
    // Let's add a new method to `ThatService`
    $delegate.doSomethingNew = function doSomethingNew() {
      $log.log('[SERVICE-2]: Let\'s try something new...');

      // We still need to do something else afterwatds, so let's use
      // the injected `ThatOtherService`
      ThatOtherService.doSomethingElse();
    };

    return $delegate;
  });
});




您可以在此demo中看到两种方法都在起作用。

09-15 13:41