Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - single service provider across multiple browser windows

I am trying to supply an alert once a task is complete - the user may be in any of multiple pages at the time. The alert should display to all pages.

I am using a service implementing BehaviorSubject The provider for which is in my app.component.ts page - single instance

In my app.component.html I have the two components, one the alert, the other that fires the alert.

<alert></alert>
<submit-service></submit-service>

The service emits to the alert component which renders the alert. This works fine, but only ever on the page that submits the service (not to any other page) - submission function is also in the alert component.

submit-service utilises public emit: BehaviorSubject<model> = new BehaviorSubject(new model());

Once the event is completed it then fires off this.emit.next(_model);

In the alert component I subscribe to the event

ngOnInit(): void {
    this.service.emit.subscribe(data=> {
           this.fireAlert(data);
        }
    });
}

so I suppose the main question is, how do I have a single service subscribed across multiple instances, across multiple pages?

EDIT 1

Apologies for the ambiguity, by page I mean separate browser window or tab i.e. window.open

like image 403
Googs Avatar asked Mar 09 '26 09:03

Googs


1 Answers

Just in case others are having this same issue - there is in fact an answer. Using global storage events allows the traversing of information across all browser tabs/windows.

In the service instead of using BehaviourSubject, the service updates or 'emits' the data to a local storage item, event listener utilising a HostListener() decorator can then listen for these udpates - which listens across all windows and tabs.

Example:

    @HostListener('window:storage', ['$event'])
    onStorageChange(ev: StorageEvent) {
       console.log(ev.key);
       console.log(ev.newValue);        
    }

See here for further information: Storage events

like image 167
Googs Avatar answered Mar 11 '26 03:03

Googs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!