Angular2 @LocalStorage
This little Angular2/typescript decorator makes it super easy to save and restore automatically a variable state in your directive (class property) using HTML5' LocalStorage.
What's new
Things that have been added in this fork:
- added
.save()
method on returned object, used in specific cases to force save object changes - support for
Array
methods that change its value (push
,pop
andshift
to be exact) - now
WebStorageService.clear()
method removes items created by this repository only - storage key prefix (
angular2ws_
by default) can be customized by changingWEBSTORAGE_CONFIG.prefix
property
Installation
-
Download the library using npm or github:
npm install --save zoomsphere.angular2-localstorage
-
Import the WebStorageModule in your app module:
;; -
If you don't like the default key prefix (
angular2ws_
) or just don't want to use any, then in yourapp.module.ts
file add the following:;WEBSTORAGE_CONFIG.prefix = ''; // no prefixWEBSTORAGE_CONFIG.prefix = 'newPrefix_';Note that it's the best to configure this right after installation, because the data saved under keys with previous prefix won't be automatically read anymore - to prevent that you can change keys of already stored data or override them manually.
How to use
-
Use the
@LocalStorage()
and/or@SessionStorage()
decorator functions. Here is where the magic happens, decorated variables' values will be restored from the storage when you reload the site!; -
Force save changes. If you need to modify stored object by not a direct assignment, then you can take advantage of
.save()
method to force save introduced changes. Example:;// this is needed to satisfy Typescript type checking; // save() method is declared in the Webstorable interface;Alternatively use
Local
(or Session)StorageService
or make straight assignment by hand.
Note: Define always a default value at the property you are using @LocalStorage
.
Note: The localstorage key is per default the property name. Define the first argument of @LocalStorage
to set different one.
Note: Please don't store circular structures as this library uses JSON.stringify to encode before using LocalStorage.
TODO
- Try to automatically handle all data manipulations using Proxy
- Add tests
Contributions are welcome!