Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Convenient way to store in session

Tags:

angular

Is there a convenient way to save in sessionStorage without the need to manually watch for property changes and update?

I have a SearchComponent with a property "query" for example.

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

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

sessionStorage.setItem('query', query);

Something like an annotation that does the job automatically would be great:

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

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

like image 274
Philipp Avatar asked May 11 '16 13:05

Philipp


1 Answers

I just tried & it is working perfectly fine for both LocalStorage & SessionStorage. Try using these steps:

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 straight forward as mentioned in docs.

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

like image 98
Apul Gupta Avatar answered Nov 16 '22 19:11

Apul Gupta