我将用思考一天后找到的解决方案来回答这个问题。
return (target, key, descriptor) => {
在里面
return function (target, key) {
通过这种方式,我可以使用
this
然后我必须找到一个好位置来初始化行为主题。在主属性的getter或setter中这样做是行不通的(我想访问
this.cats$
this.cats
).
所以我用一个新的getter解决了这个问题
cats$
这是最后的代码!
export function ObservableProperty(defaultValue = null): any {
return function (target, key) {
const accessor = `${key}$`;
const secret = `_${key}$`;
Object.defineProperty(target, accessor, {
get: function () {
if (this[secret]) {
return this[secret];
}
this[secret] = new BehaviorSubject(defaultValue);
return this[secret];
},
set: function() {
throw new Error('You cannot set this property in the Component if you use @ObservableProperty');
},
});
Object.defineProperty(target, key, {
get: function () {
return this[accessor].getValue();
},
set: function (value: any) {
this[accessor].next(value);
},
});
};
}