简体   繁体   English

如何在另一个打开的选项卡中使用组件的更改?

[英]How to use changes of a component in an another open tab?

In my project in Angular 5 when user clicks on a link a new tab of project opens then something changes in the new page. 在我在Angular 5中的项目中,当用户单击链接时,将打开一个新的项目选项卡,然后新页面中将发生某些更改。 Now how can I use these changes for the first tab? 现在如何在第一个选项卡中使用这些更改? I used Subject and Observable and save the variable for the first component. 我使用Subject和Observable并将变量保存为第一个组件。 The code goes into the first component but the first tab doesn't change, because all of these happenings are in second tab. 该代码进入第一个组件,但第一个选项卡没有更改,因为所有这些情况都在第二个选项卡中。 I want when I go to the first tab again the changes related to this component done. 我想再次进入第一个选项卡时完成与该组件相关的更改。 I don't know how to solve it, please help if you know. 我不知道如何解决,如果您知道,请帮助。 Thank you in advanced... 谢谢高级...

its not applicable to a subject to be fired in one tab and catch it in another tab, so you can simply use the storage change event as follows: 它不适用于在一个选项卡中触发并在另一个选项卡中捕获的主题,因此您可以简单地使用存储更改事件,如下所示:

window.addEventListener('storage', storageChanged);

// here listen to the changes
storageChanged(event) {
  // your code
}

in another tab, when something changed, you can add it to the storage, then it will be cached in the first event listener 在另一个选项卡中,当发生更改时,可以将其添加到存储中,然后将其缓存在第一个事件侦听器中

  localStorage.setItem('crossTabTest',data);

this approach is used when something not related to data fetched from server side, in such case, you probably will use Socket.io to receive the changes. 当某些内容与从服务器端获取的数据无关时,可以使用这种方法,在这种情况下,您可能会使用Socket.io来接收更改。

---------------------- New Edit Section ---------------------- ----------------------新增编辑部分----------------------

First Component 第一部分

ngOnInit(): void {
    window.addEventListener('storage', () => {
      const a = JSON.parse(localStorage.getItem('crossTabTest'));
      localStorage.removeItem('crossTabTest');
      console.log('Changed Value = ', a);
    });
  }

Second Component 第二部分

localStorage.setItem('crossTabTest', JSON.stringify({continue: true}));

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

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