2016-07-02 23 views
0

最近玩過Firebase RTDB,我一直在使用.once('value', v => ...)來構建我的應用程序的GUI。下面確切的代碼:Firebase RTDB`ref.once()`被多次執行

<script> 
    function onAuthCompleted(usr) { 
    var salesTxRef = firebaseApp.database().ref('/salesTx').limitToLast(5); 
    salesTxRef.once("value", salesTx => { 
     salesTx.forEach(txRef => { 
     const tx = txRef.val(); 
     const $item = $('<li></li>').html('<a href="' + txRef.key + '">$' + tx.total + ' <small>' + tx.currencyCode + '</small></a>'); 
     $('.main ul').append($item); 
     }); 
    }); 
    } 
</script> 

的問題是,如果我離開的頁面足夠長開,.once()被多次調用(每2-3小時一次)。這是一個JavaScript庫的錯誤?已知問題?有沒有我不正確的做法或我的誤解?

+2

什麼調用'onAuthCompleted()'?因爲如果這是基於Firebase身份驗證'onAuthStateChanged()'回調,則在訪問令牌刷新時將每小時調用一次。 –

回答

0

由於@Frank麪包車Puffelen在評論中指出,這個問題從調用onAuthCompleted(usr)的方法來:

firebaseApp.auth().onAuthStateChanged(function(user) { 
    if (user) { 
    if (typeof onAuthCompleted == 'function') { 
     onAuthCompleted(user); 
    } 
    } else { 
    console.log('User is not logged in. Cannot start session.'); 
    } 
}, function(error) { 
    console.log(error); 
}); 

onAuthStateChanged()被稱爲每小時刷新會話造成onAuthCompleted()被稱爲又如此註冊.once()方法多一次(每〜小時)。這導致了奇怪的感知行爲。

我可以確認.once()按預期工作,這是我對onAuthStateChange()如何工作的誤解。

謝謝,