Angular 2 - Convenient way to store in session

2020-07-13 11:27发布

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.

标签: angular
1条回答
够拽才男人
2楼-- · 2020-07-13 11:51

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

查看更多
登录 后发表回答