2 * Create and consume BroadcastChannel broadcasts
4 import {Injectable, EventEmitter} from '@angular/core';
5 import {empty} from 'rxjs';
7 interface BroadcastSub {
8 channel: any; // BroadcastChannel
9 emitter: EventEmitter<any>;
13 export class BroadcastService {
15 subscriptions: {[key: string]: BroadcastSub} = {};
17 noOpEmitter = new EventEmitter<any>();
19 listen(key: string): EventEmitter<any> {
20 if (typeof BroadcastChannel === 'undefined') {
21 return this.noOpEmitter;
24 if (this.subscriptions[key]) {
25 return this.subscriptions[key].emitter;
28 const emitter = new EventEmitter<any>();
29 const channel = new BroadcastChannel(key);
31 channel.onmessage = (e) => {
32 console.debug('Broadcast received', e.data);
36 this.subscriptions[key] = {
44 broadcast(key: string, value: any) {
45 if (typeof BroadcastChannel === 'undefined') { return; }
47 if (this.subscriptions[key]) {
48 this.subscriptions[key].channel.postMessage(value);
52 // One time use channel
53 const channel = new BroadcastChannel(key);
54 channel.postMessage(value);
60 if (typeof BroadcastChannel === 'undefined') { return; }
62 if (this.subscriptions[key]) {
63 this.subscriptions[key].channel.close();
64 this.subscriptions[key].emitter.complete();
65 delete this.subscriptions[key];