基于这个答案,我尝试在装饰器内实现另一个服务的功能。
这是我的尝试:
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)