Unable to get length of Firebase Objects

人盡茶涼 提交于 2019-12-24 11:37:46

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/28151487/unable-to-get-length-of-firebase-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!