本文介绍了Angular 2-会话中的便捷存储方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方便的方法可以保存到sessionStorage中,而无需手动监视属性更改和更新?

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

例如,我有一个带有属性查询"的SearchComponent.

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

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

每次查询或searchResult发生更改(并且还有更多属性)时,我都必须手动更新sessionStorage.

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;
    ...

我已经在此处找到了类似的解决方案.但这不适用于 sessionStorage .

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

推荐答案

我刚刚尝试过&它对于LocalStorage和& SessionStorage.尝试使用以下步骤:

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

第1步:

npm install --save angular2-localstorage

第2步:

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

第3步:

@LocalStorage() public lastSearchQuery:Object = {}

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

很简单,如文档中所述.

it is straight forward as mentioned in docs.

参考: https://github.com/marcj/angular2-localstorage

这篇关于Angular 2-会话中的便捷存储方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 10:43