2016-08-09 11 views
0

Firebaseデータベースにデータを送信し、$ state.goなどの他のアクションを行うようにデータが更新されるまで待ちます。
値が更新されるまでFirebaseが待機する

FirebaseとAngularJsを使ってどうすればいいですか?

このコードの私の部分:

var ref_achats_offres = firebase.database().ref('achats_offres'); 
    var key_achats_offres = ref_achats_offres.push().key; 
    var ladate = moment().format(); 
    var accountId = $localStorage.accountId; 
    var push_achats_offres = ref_achats_offres.child(key_achats_offres).set({ 
       cout: cout, 
       ajout_le: ladate, 
       active:true, 
       accounts: accountId, 
       id_offre : id_offre, 
       unique_code: code 
      }); 

var ref_offres = firebase.database().ref('offres'); 
ref_offres.child(id_offre).child('achats_offres').child(key_achats_offres).set(true); 
var ref_accounts = firebase.database().ref('accounts'); 
ref_accounts.child(accountId).child('achats_offres').child(key_achats_offres).set(true); 
      firebase.database().ref('accounts').child(accountId).child('credits').transaction(function(credits) { 
      return credits - cout; 
      }); 

      $scope.modal2.hide(); 
      Utils.message(Popup.checkIcon, Popup.achatOffreEffectue); 
      $state.go('mes_achats'); 
+0

私は何も知りませんAngularについてしかし、あなたが探しているものは、firebaseの "トランザクション"です:https://firebase.google.com/docs/database/web/save-data#save_data_as_transactions トランザクションのコールバックの方法はちょっと複雑ですが有効です非常に柔軟な使い方をするには、https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction – Sistr

+0

の詳細を読む必要があります。AngularFireのルーティングのベストプラクティスに関するアドバイスも参照してください。 ')[ここ](https://github.com/firebase/angularfire/blob/master/docs/guide/user-auth.md#authenticating-with-routers)。 – Kato

+0

@Katoあなたが言っていることは分かりません!私は自分のルートに間違ったことをしましたか?ありがとうございました ! –

答えて

0

set()transaction()呼び出しは約束を返します。書き込み操作が完了すると、約束が解決され、then()を実装することでこれを処理できます。

あなたは2つの設定操作は順番に実行して、ナビゲートしたい場合:

ref_accounts.child(accountId).child('achats_offres').child(key_achats_offres) 
    .set(true) 
    .then(function() { 
     firebase.database().ref('accounts').child(accountId).child('credits') 
      .transaction(function(credits) { 
       return credits - cout; 
      }) 
      .then(function() { 
       $scope.modal2.hide(); 
       Utils.message(Popup.checkIcon, Popup.achatOffreEffectue); 
       $state.go('mes_achats'); 
      }); 
    }); 

あなたがナビゲートする前にそれらを並行して両方を完全に実行したい場合:

var setPromise = ref_accounts.child(accountId).child('achats_offres').child(key_achats_offres).set(true); 
var transactionPromise = firebase.database().ref('accounts').child(accountId).child('credits') 
      .transaction(function(credits) { 
       return credits - cout; 
      }); 
Promise.all([setPromise, transactionPromise]). 
     .then(function() { 
      $scope.modal2.hide(); 
      Utils.message(Popup.checkIcon, Popup.achatOffreEffectue); 
      $state.go('mes_achats'); 
     }); 
+0

ありがとう!第二の方法は、まさに私が探していたものです。それは私が期待したことをするエレガントな方法です。ありがとうございました。 –

関連する問題