基于此答案,我尝试从装饰器内的另一个服务实现一个功能。
这是我的尝试:
export function ClearCache() {
const injectCacheService = Inject(CacheService);
return (target: any, _: string, propertyDescriptor: PropertyDescriptor) => {
injectCacheService(target, 'service'); // this is the same as using constructor(private readonly logger: LoggerService) in a class
//get original method
const originalMethod = propertyDescriptor.value;
//redefine descriptor value within own function block
propertyDescriptor.value = async function (...args: any[]) {
try {
console.log(this);
const service: CacheService = this.service;
service.clearCacheById(args[1]);
return await originalMethod.apply(this, args);
} catch (error) {
console.error(error);
}
};
};
}
但我得到了 Property 'service' does not exist on type 'PropertyDescriptor'.ts(2339)
知道我缺少什么部分吗?
更新:
tsconfig.json 具有“严格”:true。如果启用,则“this”将严格使用 PropertyDescriptor 接口。
通过更改 tsconfig.json 中的 "strict": false 修复了该问题。
如何繁殖?
不清楚您是否使用 NestJS缓存管理器包装器,如果是这样,您需要在注入时使用提供者令牌,并且类型为 Cache。
export function ClearCache() {
const injector = Inject(CACHE_MANAGER)
return (target: any, _key?: string | symbol, descriptor?: TypedPropertyDescriptor<any>) => {
injector(target, 'cacheManager')
const originalMethod = descriptor.value
descriptor.value = async function (...args: any[]) {
try {
const service: Cache = this.cacheManager
service.delete(args[1])
return await originalMethod.apply(this, args)
} catch (err) {
console.error(err)
return originalMethod(args)
}
}
}
}
如果它是不同的服务,请确保您使用正确的提供者令牌,它在当前模块范围内并已实例化。如果它不在当前模块中,请检查它是否是全局的
更新:
tsconfig.json 有"strict":true
. 如果启用,则“this”将严格使用 PropertyDescriptor 接口。
通过更改"strict": false
tsconfig.json修复了该问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句