试图从Firebase获取子记录

时间:2014-10-09 00:21:04

标签: angularjs firebase angularfire

我正处于角火种子教程阶段并尝试使用消息和子帖,由于某些奇怪的原因,当我明确地尝试显示它们时,我看不到孩子,但是当在父节点上展开时我可以看到它们安慰。这些消息在我有ng-repeat的html中正确显示,所以我知道我至少得到了这些消息,尽管没有孩子。

我认为angularfire-seed utils可能正在切碎或切片一些孩子,所以我恢复了直接的火焰基地

这就是我所拥有的:

Code:
-----
var url = fbutil.ref() + "/messages/";
var ref = new Firebase(url);

var sync = $firebase(ref).$asArray();

console.log(sync);          //this I can see as a proper $firebaseArray object
console.log(sync.length);   //this displays as 0 even though length is 3 in object above
console.log(sync[1]);       //displays as undefined 

Data:
----
messages/id1/text
        /id2/text
        /id2/post
        /id3/text

提前感谢你指出我错误的假设!

2 个答案:

答案 0 :(得分:2)

你似乎因为常见的异步问题而堕落。

这是你的代码片段:

var sync = $firebase(ref).$asArray();

console.log(sync);        //this I can see as a proper $firebaseArray object
console.log(sync.length); //this displays as 0 even though length is 3 in object above
console.log(sync[1]);     //displays as undefined 

$asArray()的呼叫不会立即返回Firebase阵列,因为数据可能需要一段时间才能从Firebase服务器上下来。因此,它会返回Firebase数组的承诺,将来会包含您的数据。

当您检查控制台中的console.log(sync)时,数据将被下载,因此它(正如您所说)是一个正确的同步数组。但是当console.log(sync.length)行运行时,数据可能尚未下载。

您可以使用$loaded()方法等待下载数据。所以:

var sync = $firebase(ref).$asArray();

console.log(sync);
sync.$loaded().then(function(sync) {
  console.log(sync.length); 
  console.log(sync[1]);     
}

答案 1 :(得分:0)

AngularFire Accessing child element methods

得到答案

简短回答:一旦分配给JS var,它就是POJO,而不再是$ firebase对象。

相关问题