我有一个 Angular 8+ 应用程序,我正在尝试使用本地存储和 session 存储。监听 session 存储或本地存储的变化。由于它的 Angular ,我正在使用事件管理器类:
constructor( private elementRef: ElementRef, private eventManager: EventManager) {
this.eventManager.addGlobalEventListener('window', 'storage', () => {
console.log('Event listener.....');
});
}
当i session 存储设置项时,上述函数不执行。仅当我转到 DevTools -> Application -> Storage
然后删除该项目时才会执行它。我在某处读到它不执行的原因是因为它无法在当前浏览器选项卡/当前窗口上执行。单击按钮时,是否有一种使事件监听器在当前窗口或浏览器选项卡上执行的方法?我正在使用 Chrome 浏览器。
最佳答案
我可以想到解决方案,例如在 localStorage
对象上创建一个服务包装器,并使用 EventManager
跟踪其他选项卡上的 localStorage 更改
本地存储.service
@Injectable({
providedIn: "root"
})
export class LocalStorageService {
private change = new EventEmitter();
constructor(private eventManager: EventManager) {
this.eventManager.addGlobalEventListener(
"window",
"storage",
({ key, oldValue, newValue }) => {
if (key) { // this mean new item has been set
this.change.emit({
type: localStorageAction.set,
key,
oldValue,
newValue
});
} else { // if key is null this mean the localstorage is cleared
this.change.emit({
type: localStorageAction.clear
});
}
}
);
}
subscribe(handler) {
return this.change.subscribe(handler);
}
clear() {
localStorage.clear();
this.change.emit({
type: localStorageAction.clear
});
}
getItem(key: string) {
return localStorage.getItem(key);
}
key(index: number) {
return localStorage.key(index);
}
get length() {
return localStorage.length;
}
removeItem(key: string) {
localStorage.removeItem(key);
this.change.emit({
type: localStorageAction.remove,
key
});
}
setItem(key: string, value) {
const oldValue = localStorage.getItem("key");
localStorage.setItem(key, value);
this.change.emit({
type: localStorageAction.set,
key,
oldValue,
newValue: value
});
}
}
现在通过此服务,您可以跟踪设置、删除项目、清除等更改
- in the demo stackblitz keep change the localStorage that why you get notify about that changes.
- you need to use this service instead of the
localStorage
object so you can get notify of the changes in the same window.- subscribe method return a subscription object.
关于javascript - 存储事件监听器不在当前窗口上执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63501129/