anon
anon

Reputation: 634

Unable to get length of Firebase Objects

I am currently using AngularFire, and trying to get the length of objects in my database.

In my Firebase, the structure looks like

popping-fire-5575
  celio
   -JgaQt-tNq-gRVIVZdCD
     artist:  
     track:  
   -JgaQuBoYk9VX3pWylx3
     artist: 
     track: 
   -JgaQuf_pyBFJ7EA1Fo_
     artist: 
     track: 

In my controller,

var profileObject = FirebaseDemo.getBroadcast($routeParams.param);
var twotwo = profileObject.$asObject();
twotwo.$bindTo($scope, 'data');

When I console log the variable 'twotwo', I get in return

Object
$$conf: Object
$id: "celio"
$priority: null
-JgaQt-tNq-gRVIVZdCD: Object
-JgaQuBoYk9VX3pWylx3: Object
-JgaQuf_pyBFJ7EA1Fo_: Object
__proto__: Object

However, I have tried all different ways to get the length, but I am not able to get to succeed. Could someone give me some directions or tips?

Upvotes: 1

Views: 1530

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

Firebase loads (and synchronizes) you data asynchronously, so by the time your console.log statement runs it is probably still busy loading the data.

Luckily AngularFire has a way to notify and run your code when the initial loading of data has completed:

var twotwo = profileObject.$asArray();
twotwo.$loaded().then(function(data) {
    console.log('Initial data loaded', data.length);
});

The two main changes from your code:

  1. Use $asArray() instead of $asObject(), since your data structure is an array
  2. Listen for the $loaded "event" and respond to that

Note that AngularFire will already notify AngularJS of any changes to the data, so you won't have to respond to $loaded if you just bind the data to the $scope and show it in your view.

Upvotes: 1

Related Questions