【问题标题】:Unable to receive storage events in angular2 application无法在 angular2 应用程序中接收存储事件
【发布时间】:2018-03-15 09:47:30
【问题描述】:

我正在关注我的应用程序的所有打开选项卡之间的通信

Communication between tabs or windows

但我没有收到事件

这是我的简单组件代码

import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
    selector: 'selector',
    template: require('./app.component.html'),
    styles: [require('./app.component.css')]
})

export class AppComponent {
 constructor(){
       // listen event
       window.addEventListener('storage', this.message_receive);
       // to trigger dummy events
        setInterval(() => {
            this.message_broadcast({a: 'rhushi'});
        }, 1000);
}
    public message_broadcast(message) {
        localStorage.setItem('message', JSON.stringify(message));
    }
    public message_receive(ev) {
        if (ev.key === 'message') {
            let message = JSON.parse(ev.newValue);
        }
    } 
}

如果我在这里犯了任何错误,请纠正我

【问题讨论】:

  • 除非您更改存储的 thr 值,否则事件不会触发

标签: angular browser tabs cross-browser local-storage


【解决方案1】:

storage 事件仅在其他选项卡中的localStorage 值更改时触发。

在上面的代码中,您每次都广播相同的 json 意味着 localStorage 中的值不会改变。仅当存储中发生值更改时才会触发存储事件。尝试发送不同的值。

【讨论】:

  • 天哪,非常感谢!试了半天才发现我的错!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-25
  • 2013-05-04
  • 2019-07-30
  • 2020-01-10
  • 1970-01-01
  • 2016-04-14
相关资源
最近更新 更多