从 Class 装饰器中访问注入的服务?打字稿/ NestJS
Access an injected service from within a Class decorator? Typescript / NestJS
是否可以从 Class 装饰器中访问注入的服务?
我想在自定义构造函数中获取服务:
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 上创建了一个示例。
是否可以从 Class 装饰器中访问注入的服务?
我想在自定义构造函数中获取服务:
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 上创建了一个示例。