我有一个类装饰器(fooAnnotation)和一个方法装饰器(barDecorator)。
import 'reflect-metadata';
function fooAnnotation(value: string){
console.log('fooAnnotation init...');
return (target: any): void => {
console.log('fooAnnotation called...');
Reflect.defineMetadata('fooAnnotation', value, target);
};
};
function barAnnotation(value: string){
console.log('barAnnotation init...');
return (target: any, propertyKey: any): void => {
console.log('barAnnotation called...');
Reflect.defineMetadata('barAnnotation', value, target);
...
const fooAnnotationValue = Reflect.getMetadata('fooAnnotation', target);
// :( fooAnnotationValue is undefined!!!
};
};
@fooAnnotation('fooAnnotationValue')
class Foo{
@barAnnotation('barAnnotationValue')
public bar: string;
}我需要的是barAnnotation必须使用fooAnnotation的值,但不幸的是typescript在方法装饰器之后计算类装饰器,所以在barAnnotation中还没有定义fooAnnotationMetadata。
方法装饰器如何检索类装饰器的值?
发布于 2021-04-15 18:45:11
因为Class Decorator已在类声明的末尾执行。所以,改变主意,你应该在属性装饰器中存储一些东西,并在类装饰器中处理所有的东西。
const innerTempPropsName = '__TempProperties__';
function fooAnnotation(value: string){
console.log('fooAnnotation init...');
return (ctor: any): void => {
console.log('fooAnnotation called...');
Reflect.defineMetadata('fooAnnotation', value, target);
const vProps = ctor[innerTempPropsName];
// now process the vProps...
delete ctor[innerTempPropsName];
};
};
function barAnnotation(value: string){
console.log('barAnnotation init...');
return (ctorPrototype: any, propertyKey: any): void => {
console.log('barAnnotation called...');
const ctor = ctorPrototype.constructor;
let vProps = ctor[innerTempPropsName];
if (!vProps) ctor[innerTempPropsName] = vProps = {};
// store temp properties into vProps
// vProps[propertyKey] = {value, }
Reflect.defineMetadata('barAnnotation', value, target);
...
};
};
@fooAnnotation('fooAnnotationValue')
class Foo{
@barAnnotation('barAnnotationValue')
public bar: string;
}https://stackoverflow.com/questions/57707455
复制相似问题