Angular 5:在Custom Decorator函数中使用Service [英] Angular 5: Using Service from inside Custom Decorator Function

查看:59
本文介绍了Angular 5:在Custom Decorator函数中使用Service的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 @Log()装饰器函数用于调试目的;

I'm creating a @Log() Decorator Function for debugging purposes;

我想要那个装饰器将其中一些逻辑委托给 LoggingService ,而这又取决于应用程序中的其他服务......

I want that Decorator to delegate some of it's logic to a LoggingService that in turn depends on other services from the app...

我一直在尝试很多不同的东西,最简单/最直接的方法是将Main(或Shared)模块的Injector缓存为模块本身的静态prop(参见下面链接的StackBlitz示例),这对于懒惰 - 已加载的模块,但不适用于急切加载的模块...

I've been trying a lot of different things, the simplest/most straightforward way was to cache the Main (or Shared) Module's Injector as a static prop on the module itself (see StackBlitz example linked below), and that works for lazy-loaded modules, but not for eagerly loaded ones...

非工作poc: https://stackblitz.com/edit/angular-j1bpvx?file=app%2Fdecorator.ts

我有没有办法在那里使用那个服务?

Is there a way I could mkae use of that Service in there??

谢谢!

推荐答案

类装饰器在类定义上执行一次。为了避免在调用 AppModule.injector.get(LoggingService)时出现争用情况,应将其移至 AppModule.injector 已经定义,即类方法。

Class decorator is executed once on class definition. In order to avoid race condition when calling AppModule.injector.get(LoggingService) it should be moved to the place where AppModule.injector is already defined, i.e. class method.

应该是

constructor.prototype[hook] = function (args) {
  const loggingService = AppModule.injector.get(LoggingService);

  loggingService.log({ ... })
  ...

这也会与 AppModule 形成紧密耦合,并防止单元被重复使用或单独测试。建议使用另一个对象来保存 injector 属性,例如分配注入器不在主要但在导入 AppModule的子模块中

This also creates tight coupling with AppModule and prevents the units from being reused or tested separately from it. It's recommended to use another object to hold injector property, e.g. assign injector not in main but in child module that is imported into AppModule:

export class InjectorContainerModule { 
  static injector: Injector;

  constructor(injector: Injector) {
    InjectorContainerModule.injector = injector;
  }
}

这篇关于Angular 5:在Custom Decorator函数中使用Service的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆