Rhushikesh
Rhushikesh

Reputation: 3700

Unable to receive storage events in angular2 application

I am working on communicating between all open tabs of my application for which I am following

Communication between tabs or windows

but I am not receive event

here is my simple component code

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

please correct me if I am making any mistake here

Upvotes: 3

Views: 1864

Answers (1)

Shubham
Shubham

Reputation: 539

The storage event only triggered if localStorage value changes in other tabs.

In above code you are broadcasting the same json each time means values in localStorage are not changing. Storage event only fired if there is a value change happens in storage. Try sending different values.

Upvotes: 6

Related Questions