【问题标题】:dependency injection into decorator functions in angularJSangularJS中的装饰器函数的依赖注入
【发布时间】:2015-12-07 09:17:54
【问题描述】:

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

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

现在假设thatService 使用它注入的thatOtherService

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

【问题讨论】:

    标签: angularjs dependency-injection decorator angular-decorator


    【解决方案1】:

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

    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) 在装饰器函数中注入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 中看到这两种方法的实际应用。

    【讨论】:

    • 我的印象是第二种选择是不可能的,因为在配置阶段服务还不可用。
    • 他们不是。但是装饰器在配置阶段没有运行(它只是注册)。它实际上是在“运行”阶段运行的,因此服务可以照常进行注入。
    • 感谢您的澄清。
    猜你喜欢
    • 2016-02-08
    • 1970-01-01
    • 2015-09-05
    • 2018-08-07
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    相关资源
    最近更新 更多