是否可以从类装饰器中访问注入(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/