Angular 2 - Convenient Session Storage

Is there a convenient way to save to sessionStorage without having to manually monitor property changes and updates?

I have a SearchComponent with a property request, for example.

export class SearchComponent { private query: String; private searchResult: SearchResult; ... 

Every time a query or searchResult changes (and there are even more properties), I have to manually update sessionStorage.

 sessionStorage.setItem('query', query); 

Something like an annotation that automatically does the job:

 export class SearchComponent { @SessionStored private query: String; @SessionStored private searchResult: SearchResult; ... 

I already found a similar solution here . But this session did not work for sessionStorage.

+5
source share
1 answer

I just tried it and it works great for both LocalStorage and SessionStorage. Try the following:

Step 1:

 npm install --save angular2-localstorage 

Step 2:

 import { LocalStorageService } from 'angular2-localstorage/LocalStorageEmitter' import { SessionStorage } from 'angular2-localstorage/WebStorage' constructor(storageService: LocalStorageService){} 

Step 3:

 @LocalStorage() public lastSearchQuery:Object = {} 

or,

 @SessionStorage() public lastSearchQuery:Object = {}; 

it is straightforward as indicated in the docs.

Link: https://github.com/marcj/angular2-localstorage

+8
source

All Articles