如何在angular2中的两个浏览器选项卡之间同步数据? [英] How do you sync data between two browser tabs in angular2?

查看:118
本文介绍了如何在angular2中的两个浏览器选项卡之间同步数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前处于一种情况,我有3个不同的组件,并且其中两个在两个两个组件之间共享,并且如果我从两个组件中的任何一个更新共享组件,我希望它们在两个组件上都得到更新有办法吗?

I am currently stuck in a situation where I have 3 different components and one of them is shared between the 2 two components and if I update shared component from any of the two components I want them to get updated on both of them is there a way to to do?

ist-component

       import {Component,bind,CORE_DIRECTIVES,OnInit} from 'angular2/core';
import {MainComponent} from 'src/MainComponent';
@Component({
    selector: 'my-app',
    directives:[MainComponent],
    template: `<h1>AppComponent {{onMain}}</h1>
    <div *ngIf="onMain == false">
       Hello
      <br> __________________________________<br>
    </div>
     <app-share></app-share>


    })

export class FirstComponent implements OnInit {}

第二部分

          import {Component,bind,CORE_DIRECTIVES} from 'angular2/core';
    import {SharedService} from 'src/shared.service';
    @Component({
        selector: 'sec-app',

        template: `<app-share></app-share>
                  <button (click)='changeCount()'></button>
`
    })

    export class SecondComponent {



        constructor(ss: SharedService) {
          this.ss = ss;
        }

        changeCount() {
          //want to change the count of shared component and also want a sync in first componen
        }
    }

共享组件

      import {Component,bind,CORE_DIRECTIVES} from 'angular2/core';
@Component({
    selector: 'app-share',

    template: `{{count}}`
})

export class ShareComponent {

   count:any;

}

现在这两个组件都在不同的路径上加载,即带有两个选项卡的浏览器,一个选项卡具有第一个组件,第二个选项卡具有第二个组件,所以现在如果要更新第二个组件,我希望两个组件之间保持同步必须反思第一个

Now both the components are on loaded on different routes i.e browser with two tabs one tab has the first component and the second tab has the second component , so now i want a sync between the two components if i update the second component it must reflect on the first one

推荐答案

使用其他两个组件中的共享组件"将仅共享代码,而不共享数据.IE.将创建共享组件"的两个实例,每个实例都有其自己的变量集.因此,对一个组件中的数据的更新将不会反映在另一组件中.这是设计使然.

Using "shared component" from the other two components will only share the code, not the data. I.e. two instantiations of "shared component" will be created, each with its own set of variables. Therefore updates to the data in one component will not be reflected in the other. This is by design.

如果需要在任何两个组件之间共享数据,则需要使用Observables.您需要通过声明一个Observable创建一个拥有共享数据的服务.所有需要访问该共享数据的其他组件都必须订阅该服务中的可观察对象.

If you need to share data between any two components you need to use Observables. You need to create a service that will own the shared data by declaring an Observable. All other components that need access to that shared data must subscribe to the observable within the service.

这篇关于如何在angular2中的两个浏览器选项卡之间同步数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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