Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...