Angular Local Storage 💾

Angular + Local Storage

Recently I was implementing local storage in Angular. I came across the marcj angular2-localstorage. He is using decorator which makes it super easy to save and restore automatically a variable state in local or session storage.

Usage

In your component just decorate your variable with @LocalStorage or @SessionStorage and you are done.

export class SomeComponent {
/** Attributes */
@LocalStorage
public variableToBeStored: string;
}

Local Storage

It’s great idea but he’s implementation is quite swollen. So I have decided to implement it on my own. Here is minimal example to understand how it works. So you can implement it on your own.

/**
* LocalStorage for storing string values
*/
export function LocalStorage(
target: Object, // The prototype of the class
decoratedPropertyName: string // The name of the property
) {
// get and set methods
Object.defineProperty(target, decoratedPropertyName, {
get: function () {
return localStorage.getItem(decoratedPropertyName) || '';
},
set: function (newValue) {
localStorage.setItem(decoratedPropertyName, newValue);
}
});
}

Session Storage

For session storage it’s alike.

/**
* SessionStorage for storing string values
*/
export function SessionStorage(
target: Object, // The prototype of the class
decoratedPropertyName: string // The name of the property
) {
// get and set methods
Object.defineProperty(target, decoratedPropertyName, {
get: function () {
return sessionStorage.getItem(decoratedPropertyName) || '';
},
set: function (newValue) {
sessionStorage.setItem(decoratedPropertyName, newValue);
}
});
}
Buy me a coffeeOut of coffee 😱, please help!