简体   繁体   中英

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 . 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. You can read about postMessage here: 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. Whenever the value in your service changes, you could send a postMessage with that value. 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.

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).

You can also combine this with localStorage to make sure that, when a new tab is opened, it can read the most recent value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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