typescript - 从类装饰器中访问注入(inject)的服务? typescript /NestJS

标签 typescript decorator nestjs

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

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

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 上创建了一个示例.

关于typescript - 从类装饰器中访问注入(inject)的服务? typescript /NestJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64380539/

相关文章:

router.navigate 后未调用 Angular 4 ngOnInit

python - 是否可以在 Django 项目中重新定义反向?

python - pygame.init() 似乎没有在装饰器中被调用

typescript - 如何在 Docker 容器内的 NestJs 应用程序中观察文件更改

javascript - API 调用时的 Angular 定位控制台错误

javascript - 使用纯 JavaScript 获取下周的开始和结束日期

swagger - Nestjs Swagger 4 的循环依赖

javascript - 开 Jest : Cannot spy the property because it is not a function; undefined given instead getting error while executing my test cases

css - 从组件方法中将样式应用于 Angular Toast

python - 在类方法和子类方法上使用 python 装饰器