|
1 |
| -# Angular2 @LocalStorage |
2 |
| - |
3 |
| -This little Angular2/typescript decorator makes it super easy to save and restore *automatically* a variable state in your |
4 |
| -directive (class property) using HTML5' LocalStorage. |
5 |
| - |
6 |
| -## What's new |
7 |
| - |
8 |
| -Things that have been added in this fork: |
9 |
| -- added `.save()` method on returned object, used in specific cases to force save object changes |
10 |
| -- support for all `Array` methods that change array object's value |
11 |
| -- now `WebStorageService.clear()` method removes items created by this repository only |
12 |
| -- storage key prefix (`angular2ws_` by default) can be customized by changing `WEBSTORAGE_CONFIG.prefix` property |
| 1 | +# Angular Storage |
| 2 | +## Decorators and services for your needs |
| 3 | + |
| 4 | +This library adds decorators that make it super easy to *automagically* save and restore variables using HTML5's `localStorage` and `sessionStorage`. It also provides Angular-Injectable Session- and LocalStorageService. |
| 5 | + |
| 6 | +## What's included? |
| 7 | +- `@LocalStorage()` and `@SessionStorage()` decorator functions |
| 8 | +- Injectable `LocalStorageService` and `SessionStorageService` providing the following methods: |
| 9 | + + `get(key: string)`: gets JSON-parsed data from HTML5 Storage |
| 10 | + + `set(key: string, value: any)`: sets data in HTML5 Storage |
| 11 | + + `remove(key: string)` removes variable with given key |
| 12 | + + `clear()`: clears Storage out of variables with set prefix |
| 13 | + + `keys`: getter for keys of stored values |
| 14 | + + `config`: getter for module config |
| 15 | +- Objects read from Storage have added `.save()` method to easily force save of made changes (configurable by `mutateObjects`) |
| 16 | +- saving support for all `Array` methods that change array object's value (configurable by `mutateObjects`) |
| 17 | +- Easy configuration of what you want (see [#configuration](#configuration) section) |
| 18 | + |
| 19 | +## Upcoming (TODO) |
| 20 | +- Handle data saved with previous prefix after its change |
| 21 | +- Encoding of saved data |
| 22 | +- Tests coverage |
| 23 | +- Cookies fallback |
| 24 | +- Automatically handle all data manipulations using [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) (?) |
| 25 | +- Take configuration from [npm config](https://www.npmjs.com/package/config)'s file (?) |
| 26 | +- Handle out of memory issues |
| 27 | +- `Storage` polyfill for NativeScript (?) |
13 | 28 |
|
14 | 29 | ## Installation
|
15 |
| - |
16 |
| -1. Download the library: `npm install --save git+https://github.com/zoomsphere/angular2-localstorage#master` |
17 |
| -2. Import the WebStorageModule in your app module: |
| 30 | +1. Download the library: `npm install --save ngx-store` |
| 31 | +2. Import the WebStorageModule in your `app.module.ts`: |
18 | 32 | ```typescript
|
19 |
| - import {Component} from 'angular2/core'; |
20 |
| - import {WebStorageModule, LocalStorageService} from 'angular2-localstorage'; |
| 33 | + import { NgModule } from '@angular/core'; |
| 34 | + import { WebStorageModule } from 'ngx-store'; |
21 | 35 |
|
22 | 36 | @NgModule({
|
23 |
| - import: [WebStorageModule] |
24 |
| - @Component({ |
25 |
| - providers: [LocalStorageService] |
| 37 | + imports: [ |
| 38 | + WebStorageModule, |
| 39 | + ], |
26 | 40 | })
|
27 | 41 | export class AppModule {}
|
28 | 42 | ```
|
29 | 43 |
|
30 |
| -3. If you don't like the default key prefix (`angular2ws_`) or just don't want to use any, then in your `app.module.ts` file add the following: |
31 |
| - ```typescript |
32 |
| - import {WEBSTORAGE_CONFIG} from 'angular2-localstorage'; |
33 |
| - WEBSTORAGE_CONFIG.prefix = ''; // no prefix |
34 |
| - WEBSTORAGE_CONFIG.prefix = 'newPrefix_'; |
| 44 | +## Custom configuration |
| 45 | +As this project uses decorating functions, it's important to provide custom configuration in `NGXSTORE_CONFIG` before Angular application load. Here are some ways to do it: |
| 46 | +1. `<script>` in `index.html` (before Angular sources) |
| 47 | + ```html |
| 48 | + <script> |
| 49 | + var NGXSTORE_CONFIG = { |
| 50 | + prefix: 'myApp.', // default: ngx_ |
| 51 | + clearType: 'prefix', // possible values: decorators, prefix, all |
| 52 | + mutateObjects: true // defines whether Array methods shall be modified to handle changes automatically and .save() method shall be added to stored objects |
| 53 | + }; |
| 54 | + </script> |
| 55 | + ``` |
| 56 | +2. If you use webpack, you can provide global variable in `webpack.json`: |
| 57 | + ```javascript |
| 58 | + plugins: [ |
| 59 | + new webpack.DefinePlugin({ |
| 60 | + NGXSTORE_CONFIG: JSON.stringify({ |
| 61 | + prefix: '' // etc |
| 62 | + }) |
| 63 | + }), |
| 64 | + ] |
35 | 65 | ```
|
36 |
| - 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. |
37 | 66 |
|
38 |
| -## How to use |
39 | 67 |
|
40 |
| -1. 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! |
| 68 | +## How to use? |
| 69 | +1. Perfectly looking but sometimes tricky: Use the `@LocalStorage()` and/or `@SessionStorage()` decorator functions. Here is where the magic happens, decorated variables are restored when user reloads the site! |
41 | 70 | ```typescript
|
42 |
| - import {LocalStorage, SessionStorage} from 'angular2-localstorage/WebStorage'; |
| 71 | + import {LocalStorage, SessionStorage} from 'ngx-store'; |
43 | 72 |
|
44 |
| - class MySuperComponent { |
45 |
| - // it will be stored under ${prefix}viewCounts name |
46 |
| - @LocalStorage() public viewCounts: number = 0; |
47 |
| - // this under name: ${prefix}differentLocalStorageKey |
48 |
| - @LocalStorage('differentLocalStorageKey') protected userName: string = ''; |
49 |
| - // and this under ${prefix}itWillBeRemovedAfterBrowserClose in session storage |
50 |
| - @SessionStorage('itWillBeRemovedAfterBrowserClose') private previousUserNames: Array<string> = []; |
| 73 | + export class MySuperComponent { |
| 74 | + // it will be stored under ${prefix}viewCounts name |
| 75 | + @LocalStorage() public viewCounts: number = 0; |
| 76 | + // this under name: ${prefix}differentLocalStorageKey |
| 77 | + @LocalStorage('differentLocalStorageKey') protected userName: string = ''; |
| 78 | + // and this under ${prefix}itWillBeRemovedAfterBrowserClose in session storage |
| 79 | + @SessionStorage('itWillBeRemovedAfterBrowserClose') private previousUserNames: Array<string> = []; |
51 | 80 |
|
52 |
| - mySuperMethod(): void { |
53 |
| - this.viewCounts++; |
54 |
| - this.userName = 'some name stored in localstorage'; |
55 |
| - this.previousUserNames.push(this.userName); |
56 |
| - for (let userName of this.previousUserNames) { |
57 |
| - // do some stuff |
58 |
| - } |
59 |
| - } |
| 81 | + constructor() { |
| 82 | + this.viewCounts++; |
| 83 | + this.userName = 'some name stored in localstorage'; |
| 84 | + this.previousUserNames.push(this.userName); |
| 85 | + for (let userName of this.previousUserNames) { |
| 86 | + // do some stuff |
| 87 | + } |
| 88 | + } |
60 | 89 | }
|
61 | 90 | ```
|
62 | 91 |
|
63 |
| -2. **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: |
| 92 | + **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: |
64 | 93 | ```typescript
|
65 |
| - import {LocalStorage, SessionStorage, Webstorable} from 'angular2-localstorage'; |
| 94 | + import { LocalStorage, SessionStorage, Webstorable } from 'ngx-store'; |
66 | 95 |
|
67 | 96 | // this is needed to satisfy Typescript type checking
|
68 | 97 | type WebstorableObject = Webstorable & Object; // save() method is declared in the Webstorable interface
|
69 | 98 | type WebstorableArray = Webstorable & Array<any>;
|
70 | 99 |
|
71 |
| - class MySuperComponent { |
72 |
| - @LocalStorage() someObject: WebstorableObject = <WebstorableObject>{}; |
73 |
| - @SessionStorage() arrayOfSomethings: WebstorableArray = [0,1,2,3,4]; |
| 100 | + export class MySuperComponent { |
| 101 | + @LocalStorage() someObject: WebstorableObject = <WebstorableObject>{}; |
| 102 | + @SessionStorage() arrayOfSomethings: WebstorableArray = [0,1,2,3,4]; |
74 | 103 |
|
75 |
| - mySuperMethod() { |
76 |
| - this.someObject.a = 1; |
77 |
| - this.someObject['b'] = 2; |
78 |
| - delete this.someObject['c']; |
79 |
| - for (let something of this.arrayOfSomethings) { |
80 |
| - something++; |
81 |
| - } |
82 |
| - // upper changes won't be saved without the lower line |
83 |
| - this.someObject.save(); |
84 |
| - this.arrayOfSomethings.save(); |
| 104 | + constructor() { |
| 105 | + this.someObject.a = 1; |
| 106 | + this.someObject['b'] = 2; |
| 107 | + delete this.someObject['c']; |
| 108 | + for (let something of this.arrayOfSomethings) { |
| 109 | + something++; |
| 110 | + } |
| 111 | + // upper changes won't be saved without the lines below |
| 112 | + this.someObject.save(); |
| 113 | + this.arrayOfSomethings.save(); |
85 | 114 | }
|
86 | 115 | }
|
87 | 116 | ```
|
88 |
| - Alternatively use `Local`(or Session)`StorageService` or make straight assignment by hand. |
89 |
| -
|
| 117 | + |
| 118 | +2. Standard way: Use `LocalStorageService` and / or `SessionStorageService`: |
| 119 | + ```typescript |
| 120 | + import { LocalStorageService, SessionStorageService } from 'ngx-store'; |
| 121 | + |
| 122 | + export class MyService { |
| 123 | + constructor( |
| 124 | + localStorageService: LocalStorageService, |
| 125 | + sessionStorageService: SessionStorageService, |
| 126 | + ) {} |
| 127 | + |
| 128 | + public saveSomeData(object: Object, array: Array<any>) { |
| 129 | + this.localStorageService.setItem('someObject', object); |
| 130 | + this.sessionStorageService.setItem('someArray', array); |
| 131 | + |
| 132 | + this.localStorageService.keys.forEach((key) => { |
| 133 | + console.log(key + ' =', this.localStorageService.getItem(key)); |
| 134 | + }); |
| 135 | + } |
| 136 | + |
| 137 | + public clearSomeData(): void { |
| 138 | + this.localStorageService.clear('decorators'); // removes only variables created by decorating functions |
| 139 | + this.localStorageService.clear('prefix'); // removes variables starting with set prefix (including decorators) |
| 140 | + this.sessionStorageService.clear('all'); // removes all session storage data |
| 141 | + } |
| 142 | + } |
| 143 | + ``` |
90 | 144 |
|
91 |
| -**Note**: Define always a default value at the property you are using `@LocalStorage`. |
| 145 | +3. Combine both ways and have fun! |
92 | 146 |
|
93 |
| -**Note**: The localstorage key is per default the property name. Define the first argument of `@LocalStorage` to set different one. |
| 147 | +**Note**: Define always a default value at the property you are using decorator. |
94 | 148 |
|
95 | 149 | **Note**: Please don't store circular structures as this library uses JSON.stringify to encode before using LocalStorage.
|
96 | 150 |
|
97 |
| -### TODO |
98 |
| -- Try to automatically handle all data manipulations using [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) |
99 |
| -- Add tests |
100 | 151 |
|
101 | 152 | **Contributions are welcome!**
|
0 commit comments