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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} | |
}); | |
} |