我在Reflect元数据中更新对象值时遇到问题,当我尝试使用Decorator初始化属性装饰器时,我成功初始化了该值,但是问题是在NgOnInit或其中的任何函数中初始化该属性时,它没有更新该值。我的组件,这就是我到目前为止所做的
属性的初始值成功
// initialized property
@BtnProp(
{key: 'btnPencarianBelanja',
icon: 'pi pi-search',
position: IBottonPosition.RIGHT,
class:'ui-button-secondary',
width: '35px',
height: '35px'})
btnPencariabtnPencarianBelanja: IToolBotton;
@BtnProps()
toolBottons: IToolBotton[];
这是我的函数装饰器
import "reflect-metadata";
import { IToolBotton } from './toolbotton.interface';
export const PROPERTY_METADATA_KEY = Symbol("BtnProp");
export function BtnProp(props: IToolBotton) {
return (target: any, propertyKey: string | symbol) => {
let value: IToolBotton;
const update = Reflect.defineProperty(
target,
propertyKey,
{
configurable: true,
enumerable: true,
get: () => {
// Return the scoped value
return !value ? props : value;
},
set:(val: IToolBotton) => {
// Update the scoped value with val || props
// but the value wont updated
value = (val !== props? val : props);
}
},
);
if(!update) {
console.log("Unable to update property");
}
const allMetadata = (
Reflect.getMetadata(PROPERTY_METADATA_KEY, target)
||
{}
);
console.log(allMetadata);
// Ensure allMetadata has propertyKey
allMetadata[propertyKey] = (
allMetadata[propertyKey]
||
{}
);
// Update the metadata with anything from updates
// tslint:disable-next-line:forin
for (const key of Reflect.ownKeys(props)) {
allMetadata[propertyKey][key] = props[key];
}
Reflect.defineMetadata(
PROPERTY_METADATA_KEY,
allMetadata,
target,
);
};
}
export function BtnProps(){
return (target: any, propertyKey: string | symbol) => {
let allMetadata: any = Reflect.getMetadata(PROPERTY_METADATA_KEY, target);
let toolbottons: IToolBotton[] = [];
for(const meta in allMetadata) {
const botton:IToolBotton = (<IToolBotton>allMetadata[meta]);
if(botton) {
toolbottons.push(botton);
}
}
const update = Reflect.defineProperty(
target,
propertyKey,
{
configurable: true,
enumerable: true,
get: () => {
// Return the scoped value
return toolbottons;
},
set:(val: IToolBotton[]) => {
// Update the scoped value with val || props
toolbottons = val
}
},
);
if(!update) {
console.log("Unable to update property");
}
}
}
试图更新ngOnInit中的值
async ngOnInit() {
....
// update value
this.btnPencariabtnPencarianBelanja.width = '10px';
console.log(this.toolBottons);// the result still same with the initialized attr property
}