I have implemented a Property Decorator that creates an Observable with static getter/setter for each property.
Usage of the decorator looks like this:
class Test {
@ObservableProperty(DEFAULT_CATS)
cats: number;
@ObservableProperty(DEFAULT_PIGS)
pigs: number;
}
The code for the decorator itself is as follows:
export function ObservableProperty(defaultValue = null): any {
return (target, key, descriptor) => {
const accessor = `${key}$`;
target[accessor] = new BehaviorSubject(defaultValue);
return Object.assign({}, descriptor, {
get: function() {
return this[accessor].getValue();
},
set: function(value: any) {
this[accessor].next(value);
},
});
};
}
Everything functions correctly with one instance of the Test
component. However, when using two instances, the test fails.
fdescribe('ObservableProperty Decorator', () => {
let test: Test;
let doppleganger: Test;
beforeEach(() => {
test = new Test();
doppleganger = new Test();
});
it('should create different observables for each props', () => {
expect(test['cats$'] === doppleganger['cats$']).toBe(false);
});
})
Due to the way the decorator operates on the prototype of component instances, the created variables are the same for both instances.
Is there a workaround for this issue using the decorator? If not, what would be a more elegant alternative?