angular - 如何在本地存储上进行活动
问题描述
我想在角度本地存储中存储一些应用程序变量(如用户名和 apikey)。但是当我更改这些值时,我想查看我的用户界面更改(导航栏上的登录按钮)。实际上,当值发生变化时,我无法捕捉到事件。
因此,我尝试在具有从 rxjs 导入的主题属性和更改属性的原始 angular localstorage 之上创建一个新服务。所以我有这个类(部分来自stackoverflow)
import { Injectable, OnDestroy } from '@angular/core';
import { Subject } from "rxjs";
import { share } from 'rxjs/operators';
@Injectable()
export class StorageService implements OnDestroy {
private onSubject = new Subject<{ key: string, value: any }>();
public changes = this.onSubject.asObservable().pipe(share());
constructor() {
this.start();
}
ngOnDestroy() {
this.stop();
}
public getStorage() {
let s = [];
for (let i = 0; i < localStorage.length; i++) {
s.push({
key: localStorage.key(i),
value: JSON.parse(<string>localStorage.getItem(<string>localStorage.key(i)))
});
}
return s;
}
public store(key: string, data: any): void {
localStorage.setItem(key, JSON.stringify(data));
// the local application doesn't seem to catch changes to localStorage...
this.onSubject.next({key: key, value: data})
}
public clear(key: string) {
localStorage.removeItem(key);
// the local application doesn't seem to catch changes to localStorage...
this.onSubject.next({key: key, value: null});
}
private start(): void {
window.addEventListener("storage", this.storageEventListener.bind(this));
}
private storageEventListener(event: StorageEvent) {
if (event.storageArea == localStorage) {
let v;
try {
if (event.newValue !== null) {
v = JSON.parse(event.newValue);
}
} catch (e) {
v = event.newValue;
}
// @ts-ignore
this.onSubject.next({key: event.key, value: v});
}
}
private stop(): void {
window.removeEventListener("storage", this.storageEventListener.bind(this));
this.onSubject.complete();
}
}
在我的登录组件中,我有这个:
const storageService = new StorageService()
if (res.status === 200) {
storageService.store('logged',JSON.stringify(await res.json()))
this.redirectAfterLogin()
}else {
storageService.clear('logged')
}
在我的导航栏组件中,我尝试了这个:
ngOnInit(): void {
window.addEventListener('storage',function (param){
console.log('here ? key is :'+param.key)
})
}
解决方案
推荐阅读
- javascript - 异步发布父子对象和关系(递归?)
- amazon-ses - Amazon SES 电子邮件身份验证需要错误
- css - 下边距及其结果
- ruby - 通过别名运行 ruby 时获取真正的工作目录
- javascript - 将数组的每个单独项作为纯字符串返回
- neovim - 在 neovim 的特定窗口中禁用语法高亮
- python - 两次调用函数,但在第二次,函数返回的第一个列表在 python 中作为参数
- c - 使用 sscanf 解析和动态分配大小不一致的子字符串
- asp.net-core - 发布到最小端点时的“未提供正文”响应
- python - Django 下载文件按钮采用路径