简体   繁体   English

如何在Angular 5中将服务数据从一个组件传递到另一个组件

[英]How to pass service data from one to another component in Angular 5

i am passing data from one component to another using service.If I am routing second component in same tab if browser then service data is aviation but if I open second component page in new tab of browser service data is not available.I am new to Angular and I am learning . 我正在使用服务将数据从一个组件传递到另一个组件。如果浏览器在同一选项卡中路由第二个组件,则服务数据是航空的,但是如果在浏览器服务数据的新选项卡中打开第二个组件页面不可用。 Angular和我正在学习。 please help me what I am missing 请帮助我我所缺少的

You cannot share variables between two browser tabs or windows, as they are isolated from each other. 您不能在两个浏览器选项卡或窗口之间共享变量,因为它们彼此隔离。 If you open the same app in two tabs, then you've got two apps running and neither are aware of the other. 如果您在两个标签中打开同一个应用程序,则说明您有两个应用程序在运行,而另一个都不知道。

However, you can have inter-tab communication by using the postMessage API. 但是,可以使用postMessage API进行标签间通信。 You can read about postMessage here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage . 您可以在此处阅读有关postMessage信息: https : //developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Using postMessage you can send a message to all the tabs in the curren domain, and also receive message from them. 使用postMessage可以将消息发送到curren域中的所有选项卡,也可以从中接收消息。 Whenever the value in your service changes, you could send a postMessage with that value. 每当服务中的值更改时,您都可以发送带有该值的postMessage Also, in the service you must listen to the message event, filter it and, if some window has sent a change of the value, set it as the current value in the service. 另外,在服务中,您必须侦听message事件,对其进行过滤,如果某个窗口发送了该值的更改,则将其设置为服务中的当前值。

When doing this you must make sure not to send another postMessage when you're updating the current value due to a received message, or you'll enter an infinite loop (tab 1 sends a message, tab 2 receives it, changes its value, broadcasts that value, tab 1 receives the message, updates the value, broadcasts the same value, tab 2 receives the message ... and so on). 执行此操作时,必须确保由于收到消息而在更新当前值时不要发送另一个postMessage ,否则您将进入无限循环(选项卡1发送消息,选项卡2接收消息,更改其值,广播该值,选项卡1接收消息,更新该值,广播相同的值,选项卡2接收消息...,依此类推。

You can also combine this with localStorage to make sure that, when a new tab is opened, it can read the most recent value. 您还可以将其与localStorage结合使用,以确保在打开新选项卡时,它可以读取最新值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM