Daniel Zuzevich Daniel Zuzevich - 3 months ago 8
AngularJS Question

Firebase Database Delay Of Received Information

This should be pretty easy for someone with firebase experience. I am using firebase alongside Angular JS and Node, and have a pretty basic function in my Controller set to fire when the user clicks a button. All the function does is grab some data from the Firebase database. It works, but takes two clicks for this data to be displayed to the screen.

It is not a matter of clicking and giving it a few seconds to load, it just does not work, unless you click it a second time. Upon clicking for the second time, the data is displayed immediately. It has to be something pretty basic, where I am just not understanding what's happening. Code is below.

$scope.databaseCall = function(){
var ref = firebase.database().ref("users/MikeG1499");
ref.on('value',function(snapshot){
$scope.doesThisWork = snapshot.child("name").val();
});
}


<div>
<button ng-click="databaseCall()" class="btn btn-md btn-success">TESTING</button>

<span>{{doesThisWork}}</span>
</div>

Answer

Since the Firebase Database data is loaded/synchronized asynchronously, AngularJS is not listening for it when you update the scope.

The solution is to make AngularJS aware of when you update the scope:

var ref = firebase.database().ref("users/MikeG1499");
ref.on('value',function(snapshot){ 
  $timeout(function() {
    $scope.doesThisWork = snapshot.child("name").val();
  });
});

You can instead also use AngularFire, which does this and much more for you.

Comments