Angular 2 - 跨多个浏览器窗口的单一服务提供商 [英] Angular 2 - single service provider across multiple browser windows

查看:196
本文介绍了Angular 2 - 跨多个浏览器窗口的单一服务提供商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在任务完成后提供警报 - 用户当时可能处于多个页面中的任何一个页面。警报应显示在所有页面上。

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.

我正在使用一项服务实现 BehaviorSubject
提供商这是在我的app.component.ts页面 - 单个实例

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

在我的app.component.html中我有两个组件,一个是警报,另一个是触发警告。

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 使用
public emit:BehaviorSubject< model> = new BehaviorSubject(new model());

一旦事件完成,它就会触发 this.emit .next(_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?

编辑1

歧义的道歉,页面我的意思是单独的浏览器窗口或标签即 window.open

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

推荐答案

以防其他人是有同样的问题 - 实际上有一个答案。
使用全局存储事件允许跨所有浏览器选项卡/窗口遍历信息。

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.

在服务中而不是使用 BehaviourSubject ,服务将数据更新或发送到本地存储项,使用 HostListener()装饰器的事件监听器可以监听这些udpates - 监听所有窗口和标签。

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.

示例:

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

详情请见此处:存储事件

这篇关于Angular 2 - 跨多个浏览器窗口的单一服务提供商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆