2017-05-03 124 views
2

我有兩個不同的頁面發送者和接收者,並且在開放在兩個不同的突片共享數據兩者之間的頁面/標籤頁angular2

一個標籤瀏覽器的具有http://localhost:4200/sender

第二個標籤已擁有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); 
    } 
} 

數據Service.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(); 
    } 
} 

現在的數據共享服務問題是組件被加載到瀏覽器中的兩個不同的選項卡/頁,這兩個選項卡/頁沒有關係,他們有自己的實例聲明等任何服務(主題,行爲),觀察家不能分享這兩個選項卡之間的數據,以便我如何能共享數據的兩個頁面之間,並且改變必須是同步或反射的接收器頁面上

+0

我想這個問題是類似http://stackoverflow.com/questions/43737772/how-do-you-sync-data-between-two-browser-tabs-in-angular2 –

回答

0

您可以在任何時候ping通你的後端服務,以獲取最新的更新數據。

假設你在第一個選項卡更新數據,並且希望它在另一個標籤。當您打開第二個選項卡(即集中第二個選項卡),你給後端的請求(呼叫服務)曾經那麼它將獲取你這是從第一片更新的第二個選項卡上的最新數據。

你會得到很多帖子,觀察標籤關注事件。

http://www.thefutureoftheweb.com/blog/detect-browser-window-focus