2017-07-17 91 views
3


我想創建一個提供程序,這是我的應用程序和Firebase之間唯一的接口。
Im new to promises im sorry,if im doing something horrible wrong。我想要做的就是在每次某個值發生更改時,在我的FirebaseProvider之外調用功能

FirebaseProvider:
Ionic Firebase承諾,每當價值發生變化時調用函數

onUpdateLobby(key){ 
 
    return new Promise((resolve,reject)=>{ 
 
     firebase.database().ref("/games").child(key).on('value',(snap)=>{ 
 
     console.log("update"); 
 
     if(snap) resolve(snap.val()); 
 
     else reject(Error("onUpdateLobby Error")); 
 
     }); 
 
    }); 
 
    }


Testpage

this.db.onUpdateLobby('test').then((snap) => { 
 
    console.log(snap); 
 
    // do stuff with the data 
 
}).catch((err) => { 
 
    console.log(err); 
 
});

在我的TestPage中,我想Console.Log每次有事情發生變化時記錄整個對象,這甚至有可能嗎? (我想和火力地堡只是通過我的供應商進行溝通)改變值3次後

我的控制檯看起來像:

  • 更新(從供應商)
  • asdasdasd (從TestPage )
  • 更新(來自提供者)
  • 更新(從供應商)
  • 更新(從供應商)

謝謝!

+0

在TestPage你在哪裏運行該代碼?有一點需要注意的是承諾不像可觀察的那樣工作。你需要調用函數來獲得響應。 – SimplyComplexable

回答

2

正如我的評論所述。我認爲你遇到的問題是你要退回一個承諾而不是EventEmitter。改爲嘗試下面的代碼。

火力地堡提供者:

lobbyChanges = new EventEmitter<string>; 

onUpdateLobby(key){ 
    firebase.database().ref("/games").child(key).on('value',(snap)=>{ 
     console.log("update"); 
     if (snap) this.lobbyChanges.emit(snap.val()); 
     else this.lobbyChanges.error(Error("onUpdateLobby Error")); 
    }); 
} 

TestPage:

this.db.lobbyChanges.subscribe(
    (snap) => { 
     console.log(snap); 
     // do stuff with the data 
    (err) => { 
     console.log(err); 
}); 
this.db.onUpdateLobby('test') 
1

我認爲這是實現你想要的東西的一種方式。

在您的FirebaseProvider中創建一個公共函數(listenToGamesNode()),該函數將回調函數作爲參數以及子節點密鑰。此函數註冊一個偵聽器,並在節點更改時調用提供的回調函數。

stopListeningToGamesNode()函數刪除偵聽器。

FirebaseProvider:

export class FirebaseProvider{ 
    private gamesRef:any; 

    constructor(){ 
     this.gamesRef = firebase.database().ref('games'); 
    } 

    listenToGamesNode(key, callback){ 
     this.gamesRef.child(key).on('value', callback); 
    } 

    stopListeningToGamesNode(key){ 
     try{ 
      this.gamesRef.child(key).off('value'); 
     } 
     catch(e){ 
      // Handle error 
     } 
    } 
} 

然後在你的TestPage成分,注入FirebaseProvider。使用生命週期事件ionViewWillEnter開始監聽,並使用ionViewWillLeave停止監聽節點。

TestPage:

export class TestPage{ 
    private key:string = 'test'; 

    constructor(private firebaseProvider: FirebaseProvider){} 

    ionViewWillEnter(){ 
     this.firebaseProvider.listenToGamesNode(this.key, this.callback); 
    } 

    ionViewWillLeave(){ 
     this.firebaseProvider.stopListeningToGamesNode(this.key); 
    } 

    private callback(snapshot){ 
     if(snapshot.exists()){ 
      console.log(snapshot.val()); 
     } 
     else{ 
      // Handle missing node 
     } 
    } 
} 
相關問題