Ionic Firebase Promise, call a function every time a value has changed
I want to create a Provider that is the only interface between my App and Firebase.
Im new to promises im sorry if im doing something terrible. What I want to do is call a function outside of my FirebaseProvider whenever a certain value changes.
FirebaseProvider:
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"));
});
});
}
test page
this.db.onUpdateLobby('test').then((snap) => {
console.log(snap);
// do stuff with the data
}).catch((err) => {
console.log(err);
});
In my TestPage I would like to Console.Log the whole object every time something changed, is it possible? (I only want to communicate with Firebase through my provider)
My console after changing the value 3 times looks like this:
- update (from vendor)
- asdasdasd (from TestPage)
- update (from vendor)
- update (from vendor)
- update (from vendor)
Thank!
source to share
As mentioned in my comment. I think the problem you are having is that you are returning a promise and not EventEmitter
. Try using the following code instead.
Firebase Provider:
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"));
});
}
test page:
this.db.lobbyChanges.subscribe(
(snap) => {
console.log(snap);
// do stuff with the data
(err) => {
console.log(err);
});
this.db.onUpdateLobby('test')
source to share
I think this is one way to achieve what you want.
Create a public function ( listenToGamesNode()
) in FirebaseProvider
that takes a callback function as an argument along with the child node -key. This function registers a listener and calls the provided callback when node changes.
stopListeningToGamesNode()
-function removes the listener.
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
}
}
}
Then in your TestPage component enter FirebaseProvider
. Use lifecycle events ionViewWillEnter
to start listening and ionViewWillLeave
stop listening to node.
test page:
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
}
}
}
source to share