如何访问装饰器中方法参数的值?
export const NullParameterCheck = (target: Object, key: string, index: number) => {
// how to get the value of the marked parameter in this case 'model'
// ... do something with that value here.
}
这就是我使用它的方式
public SetToolbar(@NullParameterCheck model: ToolbarModel): void {
}
我能找到的只是如何声明参数装饰器并记录其每个参数
谢谢。
装饰器在声明类时调用,而不是在调用方法时调用。您可以替换原始方法来拦截和更改原始参数,但是您不能从参数装饰器替换该方法,只能从方法装饰器执行此操作,因此您需要将装饰器添加到函数中:
const NullParameterCheck = (index: number) => (target: any, key: string, propDesc: PropertyDescriptor) => {
let originalFunction: Function = propDesc.value;
propDesc.value = function () {
let argValue = arguments[index];
let newArgs = [];
for (let i = 0; i < arguments.length; i++)newArgs.push(arguments[i]);
newArgs[index] = argValue || {};
return originalFunction.apply(this, newArgs);
};
return propDesc;
}
class ToolbarModel { }
class x {
@NullParameterCheck(0)
public SetToolbar( model: ToolbarModel): void {
console.log(model);
}
}
new x().SetToolbar(null);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)