Angular Property Decorator only creates one property instance per Class Type

Viewed 2216

I'm using a Property Decorator to create an Observable with static getter/setter for every property.

In the end you can use the decorator in this way

class Test {
    @ObservableProperty(DEFAULT_CATS) 
    cats: number;

    @ObservableProperty(DEFAULT_PIGS) 
    pigs: number;
}

The actual code for the decorator is

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);
            },
        });
    };
}

Now everything works fine with one instance of the Test component.

But with two instances this test actually 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);
    });
})

Because the decorator works on the prototype of the component instances the created variables are exactly the same one.

How can I get around this issue?

If it cannot be done with a decorator what's an elegant alternative way?

1 Answers
Related