2016-12-17 78 views
0

現在我有一個間隔,用於檢查我的可觀察值是否每隔1秒更改一次。我知道這不是最有效的方式,但我無法弄清楚如何監聽狀態變化,並直接在組件中運行一個函數。這裏是我現在的間隔:如何聆聽組件內可觀察的更改

更新1: 我現在使用訂閱,但這仍然不適合我。我從已訂閱的可觀察值發送可觀察的Firebase對象。這是我的問題所在嗎?

服務

private ReadyObs; 

    SetRoom(){ 
    this.Room = this.AngularFire.database.object('/Rooms/ABC1'); 
    this.Room.subscribe(snap => { 
     if(snap.$value !== null){ 
      this.Ready = this.AngularFire.database.object(`/Rooms/${player.room}/Ready`); 
     } 
     } 

    checkReady(){ 
     return this.ReadyObs; 
    } 

組件

private ReadyObs=this.main.checkReady(); 

    //Always results with still not ready even though its true 
    this.ReadyObs.subscribe((result) =>{ 
    if(result === true) 
     console.log("Ready to use"); 
    else 
     console.log("Still not ready"); 
    }); 

回答

1

如果checkReady()將返回一個可觀察你可以訂閱它得到改變。

this.checkReady() 
    .subscribe(result => { 
    if (result === true) { 
     console.log("Ready"); 
    } else { 
     console.log("Still not ready"); 
    } 
    }, (error) => { 

    }); 
+0

我試過這個,但由於某種原因,這對我不起作用我會更新我的代碼 –