在Nest.js中,如何在装饰器中获取服务实例?
CustomDecorator
中,如何访问Nest.js中定义的服务实例?
export const CustomDecorator = (): MethodDecorator => {
return (
target: Object,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
) => {
// Here, is possibile to access a Nest.js service (i.e. TestService) instance?
return descriptor;
}
};
解决方案
聚会迟到了,但因为我遇到了类似的问题(Use global nest module in decorator),偶然发现了这个问题。
import { Inject } from '@nestjs/common';
export function yourDecorator() {
const injectYourService = Inject(YourServiceClass);
return (target: any, propertyKey: string, propertyDescriptor: PropertyDescriptor) => {
// this is equivalent to have a constructor like constructor(yourservice: YourServiceClass)
// note that this will injected to the instance, while your decorator runs for the class constructor
injectYourService(target, 'yourservice');
// do something in you decorator
// we use a ref here so we can type it
const yourservice: YourServiceClass = this.yourservice;
yourservice.someMethod(someParam);
};
}
相关文章