这个问题是因为在Angular 15及更高的版本中,不能在属性上使用自定义修饰符。这是因为在这个版本中,Angular已经更改了它的编译器,以便更严格地遵守TypeScript规范。
解决这个问题的一个简单解决方法是在装饰器上使用一个set函数,并在set函数中对属性进行处理。
例如,如果你有一个这样的装饰器:
function MyCustomDecorator(target: any, name: string) {
const key = `__${name}__`;
Object.defineProperty(target, name, {
get: function () {
return this[key];
},
set: function (val) {
this[key] = `My custom value is ${val}`;
}
});
}
你需要更改它,以便使用一个set函数来处理属性:
function MyCustomDecorator(target: any, name: string) {
const key = `__${name}__`;
Object.defineProperty(target, name, {
get: function () {
return this[key];
},
set: function (val) {
this[key] = `My custom value is ${val}`;
}
});
}
class MyClass {
@MyCustomDecorator
public myProperty: string;
}
const myInstance = new MyClass();
myInstance.myProperty = 'Some value'; // 这里将会调用set函数
console.log(myInstance.myProperty) // 输出: "My custom value is Some value"
这个方法会在当前版本的Angular中起作用。如果你想在属性上使用自定义修饰符,你需要使用更早的Angular版本。