hik*_*neh 2 decorator node.js typescript nestjs
基于这个答案,我尝试在装饰器内实现另一个服务的功能。
这是我的尝试:
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);
}
};
};
}
Run Code Online (Sandbox Code Playgroud)
但我得到了Property 'service' does not exist on type 'PropertyDescriptor'.ts(2339)
知道我缺少哪一部分吗?
更新:
tsconfig.json 有“strict”:true。如果启用,则“this”将严格使用PropertyDescriptor 接口。
通过更改 tsconfig.json 中的 "strict": false 修复了该问题。
如何重现?
小智 5
目前尚不清楚您是否使用 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)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果它是不同的服务,请确保您使用正确的提供者令牌,它位于当前模块范围内并已实例化。如果它不在当前模块中,请检查它是全局的
更新:
tsconfig.json 有"strict":true. 如果启用,则“this”将严格使用PropertyDescriptor 接口。
"strict": false通过更改tsconfig.json修复了该问题。
| 归档时间: |
|
| 查看次数: |
7569 次 |
| 最近记录: |