问题
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