How do you sync data between two browser tabs in angular2?

試著忘記壹切 提交于 2019-12-12 04:47:33

问题


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 {}

2nd-component

          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
        }
    }

shared-component

      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


回答1:


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.

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.



来源:https://stackoverflow.com/questions/43737772/how-do-you-sync-data-between-two-browser-tabs-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!