无法在angular2应用程序中接收存储事件

时间:2017-10-04 05:09:37

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

我正在处理我正在关注的应用程序的所有打开标签之间的通信

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);
        }
    } 
}

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

1 个答案:

答案 0 :(得分:2)

storage事件仅在localStorage值在其他标签中更改时触发。

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