I am working on incorporating TypeScript Decorators in an Angular application to store data in local storage. This is my current goal:
export function Storage() {
return function (target, key): any {
// property value
let _val = target[key];
// property getter
const getter = function () {
const data = localStorage.get(key);
if (data) {
return data;
}
localStorage.set(key, _val);
return _val;
};
// property setter
const setter = function (newVal) {
localStorage.set(key, newVal);
console.log('Setting', newVal);
_val = newVal;
};
// Create new property with getter and setter
Object.defineProperty(target, key, {
configurable: true,
enumerable: true,
get: getter,
set: setter
});
};
}
And here is how you can use it:
Component 1:
....
@Storage() userSession: any = {val: ''};
ngOnInit() {
this.userSession.val = "some value"
}
....
Component 2:
....
@Storage() userSession: any;
ngOnInit() {
console.log('Stored value is', this.userSession);
// expected: {val: 'some value'}
// prints: {val: ''}
}
....
Based on my understanding, the property setter is only triggered when there is any assignment to the object itself, not its property. This is why the suggested method works:
Object.assign(this.userSession, {val: 'some value'});
or
this.userSession = {val: 'some value'}
console.log(this.userSession) // prints: {val: 'some value'}
However, this defeats the purpose I am aiming for. Therefore, my question is, how can I modify the decorator function to allow for this syntax?
this.userSession.val = 'some value';
Any guidance would be greatly appreciated.