问题描述
我使用的是 AngularFire 0.8
I'm using AngularFire 0.8
我调用了以下函数来获取数组的实例.
I called the following function to get an instance of an array.
var test = $firebase(new Firebase(URL)).$asArray();
当我 console.log 'test' 时,我得到以下信息(见截图).
When I console.log 'test', I get the following (see screenshot).
看起来 test 是一个数组.但是,当我执行console.log(test[0])"时,我得到未定义.
It looks like test is an array. However, when I do "console.log(test[0])", I get undefined.
为什么不测试具有两个元素的数组,例如 console.log(test) 似乎表明它应该是???
Why isn't test an array with two elements like console.log(test) seems to show it should be???
帮助!!
推荐答案
很可能是在加载数据之前对数组调用 console.log
.要访问数组中的数据,必须等到数据加载完毕.
Most likely you're calling console.log
on the array before the data is loaded.To access the data in the array, you have to wait until the data is loaded.
要在代码中做到这一点,您可以使用以下结构:
To do that in code, you use this construct:
var test = $firebase(new Firebase(URL)).$asArray();
test.$loaded().then(function(array) {
console.log(array[0]);
});
更新
这个答案得到了比我认为值得的更多的赞成票.当您使用 AngularJS 和 AngularFire 时,如果您使用 console.log
调试加载的数据,通常是一个不祥之兆.
Update
This answer gets more upvotes than I think it's worth. When you're using AngularJS and AngularFire, it is often a bad omen when you use console.log
to debug the data that is loaded.
AngularFire处理异步操作的文档现在不得不说:
记录数据的最简单方法是使用 Angular 的 json
过滤器在视图中打印数据.
{{ data | json }}
AngularFire 会在完成数据加载时通知 Angular 编译器,因此无需担心何时可用.
AngularFire tells the Angular compiler when it has finished loading the data, so there is no need to worry about when it be available.
这篇关于angularfire - 为什么我不能循环遍历 $asArray 返回的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!