【发布时间】:2019-09-07 13:35:46
【问题描述】:
我有 angular,ionic 4 localstorage 的问题。当我从一个页面将数据保存在 localstorage 上,并想将数据显示到另一个页面时,我需要重新加载页面以使其正常工作。我考虑过检查对于页面中的本地存储更改,我想显示数据。您知道如何检测角度 7、离子 4 中本地存储的更改吗?
【问题讨论】:
标签: angular local-storage ionic4
我有 angular,ionic 4 localstorage 的问题。当我从一个页面将数据保存在 localstorage 上,并想将数据显示到另一个页面时,我需要重新加载页面以使其正常工作。我考虑过检查对于页面中的本地存储更改,我想显示数据。您知道如何检测角度 7、离子 4 中本地存储的更改吗?
【问题讨论】:
标签: angular local-storage ionic4
您可以拥有一个服务,该服务负责在属性设置器和获取器中设置和检索本地存储的值。
模板绑定到属性后,您各自的组件将根据更改检测进行更新。
例如,这是您想要在 localStorage 中设置一个属性的服务。
import { Injectable } from '@angular/core';
@Injectable()
export class SetStorageService {
private _localItem: string = '';
constructor() { }
set localItem(value: string) {
this._localItem = value;
localStorage.setItem('localItem', value);
}
get localItem() {
return this._localItem = localStorage.getItem('localItem')
}
}
您的组件如下:
export class AppComponent {
name = 'Angular';
private _item: string = ""
constructor(private _storageService: SetStorageService) {}
set item(value) {
this._item = value;
this._storageService.localItem = value;
}
get item() {
return this._item = this._storageService.localItem;
}
addValue() {
this.item = "New Value"
}
}
您的视图将绑定到最终从 localStorage(通过服务)获取其数据的属性。
<p>
Item in App component - <b>{{item}}</b>
</p>
在此处查看示例:
https://stackblitz.com/edit/angular-pgdz8e?file=src%2Fapp%2Fapp.component.ts
【讨论】:
localStorage.setItem(key, value);
localStorage.getItem(key);
要删除你可以使用
ngOnDestroy() {
localStorage.removeItem('key');
}
【讨论】:
我认为您应该使用 rxjs 流来完成此操作。
private storageSub= new Subject<string>();
...
watchStorage(): Observable<any> {
return this.storageSub.asObservable();
}
setItem(key: string, data: any) {
localStorage.setItem(key, data);
this.storageSub.next('added');
}
removeItem(key) {
localStorage.removeItem(key);
this.storageSub.next('removed');
}
【讨论】:
要检查storage 中的值是否已更改,您可以将listener 添加到event of the storage,如下所示:
document.addEventListener('storage', (e) => {
if(e.key === 'theyKeyYouWant') {
// Do whatever you want
}
});
【讨论】: