我正在使用两个装饰器。一个是类装饰器,另一个是方法装饰器。
类装饰器定义了元数据,我想在方法装饰器中访问该元数据。
类装饰器:
方法装饰器:
这是我的Class定义:
问题:
MethodDecorator 中的以下行返回
问题:
如何从 MethodDecorator 访问 ClassDecorator 定义的元数据?
类装饰器:
function ClassDecorator(topic?: string): ClassDecorator {
return (target) => {
Reflect.defineMetadata('topic', topic, target);
// I've also tried target.prototype instead of target
return target;
};
}
方法装饰器:
interface methodDecoratorOptions {
cmd: string
}
function MethodDecorator(options: decoratorOptions) {
return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
// HERE IS MY PROBLEM
console.log('metaData is: ', Reflect.getMetadata('topic', target));
}
}
这是我的Class定义:
@ClassDecorator('auth')
export class LoginClass {
@MethodDecorator({
cmd: 'login'
})
myMethod() {
console.log('METHOD CALLED');
}
}
问题:
MethodDecorator 中的以下行返回
metaData is: undefined
。为什么它是 undefined?console.log('metaData is: ', Reflect.getMetadata('topic', target));
问题:
如何从 MethodDecorator 访问 ClassDecorator 定义的元数据?