2017-07-17 15 views
3


私のAppとFirebaseの間の唯一のインターフェイスであるプロバイダを作成したいと思っています。
Im新しいことを約束することは間違いです。何をしたいのですか?特定の値が変更されるたびにのFirebaseProvider外にある関数を呼び出してください。

FirebaseProvider:
Ionic Firebase Promise、値が変更されるたびに関数を呼び出す

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になりたいと思いますが、これは可能ですか? (プロバイダから)

  • 更新
  • asdasdasd (TestPageから:値3回を変更した後

    マイコンソールを(私はちょうど私のプロバイダを経由してFirebaseと通信したいが)のように見えます)

  • 更新
  • 更新(プロバイダから)
  • 更新(プロバイダから)

ありがとう!

+0

?注意すべきことの1つは、約束が観察可能なようには働かないことです。応答を取得するには関数を呼び出す必要があります。 – SimplyComplexable

答えて

2

私のコメントに記載されています。あなたがやっている問題は、EventEmitterではなく約束を返すということです。代わりに次のコードを試してください。

Firebaseプロバイダ:

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() -functionはリスナーを削除します。

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: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 
     } 
    } 
} 
関連する問題