无法获取 Firebase 对象的长度 [英] Unable to get length of Firebase Objects

查看:16
本文介绍了无法获取 Firebase 对象的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 AngularFire,并试图获取数据库中对象的长度.

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

在我的 Firebase 中,结构看起来像

In my Firebase, the structure looks like

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

在我的控制器中,

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

当我控制台记录变量twotwo"时,我得到回报

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?

推荐答案

Firebase 以异步方式加载(并同步)您的数据,因此当您的 console.log 语句运行时,它可能仍在忙于加载数据.

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

幸运的是,AngularFire 有一种方法可以在初始数据加载完成时通知并运行您的代码:

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);
});

代码的两个主要变化:

  1. 使用 $asArray() 而不是 $asObject(),因为你的数据结构是一个数组
  2. 监听$loaded事件"并响应
  1. Use $asArray() instead of $asObject(), since your data structure is an array
  2. Listen for the $loaded "event" and respond to that

请注意,AngularFire 已经将数据的任何更改通知 AngularJS,因此如果您只是将数据绑定到 $scope 并将其显示在您的视图中.

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.

这篇关于无法获取 Firebase 对象的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆