angularJS中对decorator函数的依赖注入



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

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

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

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

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

1) 从ThatService:暴露ThatOtherService

.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) 在decorator函数中注入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;
  });
});

在这个演示中,您可以看到这两种方法都在发挥作用。

相关内容

  • 没有找到相关文章

最新更新