从类装饰器中访问注入的服务?打字稿/ NestJS

问题描述

是否可以从类装饰器中访问注入的服务?

我想在自定义构造函数获取服务:

function CustDec(constructor: Function) {
  var original = constructor;

  var f: any = function (...args) {
    // I want to get injectedService here. How?
    // I've tried things like this.injectedService but that doesn't work
    return new original(...args);
  }

  f.prototype = target.prototype;
  return f;
}

@CustDec
@Injectable()
class MyService {
  constructor(
    private readonly injectedService: InjectedService,) {}
}

解决方法

基于official class-decorator docs,以下是一种可行的方法:

function CustDec<T extends new(...args: any[]) => {}>(Target: T) {
    return class extends Target {
        constructor(...args: any[]) {
            super(...args);
            (args[0] as InjectedService).doSomething();
        }
    }
}

@CustDec
@Injectable()
class MyService {
  constructor(
    private readonly injectedService: InjectedService,) {}
}

我还在TS-Playground上创建了一个示例。