【发布时间】:2017-10-01 08:22:15
【问题描述】:
我有两个不同的页面发送者和接收者,并在两个不同的标签
中打开即浏览器的一个标签有http://localhost:4200/sender
即第二个标签页的borwser有http://localhost:4200/receiver
receiver.component.ts
此组件将检测/同步将由第二个页面/选项卡应用的更改,即它将根据布尔属性 OnMain
更改内容 import {Component,bind,CORE_DIRECTIVES,OnInit} from 'angular2/core';
import {MainComponent} from 'src/MainComponent';
import {SharedService} from 'src/shared.service';
@Component({
selector: 'my-app',
directives:[MainComponent],
template: `<h1>AppComponent {{onMain}}</h1>
<div *ngIf="onMain == false">
Hello
<br>Show this content if false<br>
</div>
})
export class AppComponent implements OnInit {
onMain: Boolean;
constructor(ss: SharedService) {
this.onMain = false;
this.ss = ss;
}
ngOnInit() {
this.subscription = this.ss.getMessage()
.subscribe(item => this.onMain=item);
}
}
sender.component.ts
具有发送者组件的页面/选项卡想要更改第一页/选项卡的内容
import {Component,bind,CORE_DIRECTIVES} from 'angular2/core';
import {SharedService} from 'src/shared.service';
@Component({
selector: 'main-app',
template: `<h1> Sencond Page Component</h1>
<button (click)="changeFirstPageMenu()">Hide Menu</button>
`
})
export class MainComponent {
constructor(ss: SharedService) {
this.ss = ss;
}
changeFirstPageMenu() {
this.ss.sendMessage(true);
}
}
数据服务.ts 这是一个共享服务,其数据必须由一个页面更改,更改将同步到另一个页面(即接收方)
import { Subject } from 'rxjs/Subject';
@Injectable()
export class LandingService {
private subject = new Subject<any>();
sendMessage(message: any) {
this.subject.next({ text: message });
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
现在的问题是 组件 加载在浏览器的两个不同选项卡/页面上,这两个选项卡/页面没有关系,它们声明了自己的实例,因此任何 服务(主题,行为),观察者无法在这两个选项卡之间共享数据,所以我如何在两个页面之间共享数据,并且更改必须同步或反映在接收器上页面
【问题讨论】: