问题描述
我正在尝试在 AngularFire 中使用 .numChildren()
,但不确定我是否正确使用.
I'm trying to use .numChildren()
in AngularFire, but not sure I'm doing it correctly.
function getServiceProviders(serviceId) {
var serviceProviders = ref.child('services').child(serviceId).child('providers');
return serviceProviders.numChildren();
}
我收到以下错误:
TypeError: e.numChildren is not a function
不确定这是不是因为我使用 Browserify,或者我只是试图错误地访问 numChildren
.
Not sure if this is due to me using Browserify, or I'm just trying to access numChildren
incorrectly.
感谢任何帮助.提前致谢!
Any help is appreciated. Thanks in advance!
推荐答案
您的代码片段不使用 AngularFire,它只使用 Firebase JavaScript SDK.尽管您的项目无疑使用了 AngularFire,但与这个问题无关.
当您查看 .child 的文档时()
方法在 Firebase JavaScript SDK 中,您会看到它返回一个 Firebase 参考.如果您进一步查看该类,您应该注意到它没有 numChildren
方法.
When you look at the documentation for the .child()
method in the Firebase JavaScript SDK, you'll see that it returns a Firebase reference. And if you look further into that class, you should notice that it doesn't have a numChildren
method.
numChildren
是仅适用于 DataSnapshot
对象,其中您可以进入任何 on(...
事件处理程序.
所以:
serviceProviders.on('value', function(snapshot) {
console.log(snapshot.numChildren());
}
由于快照将异步加载,因此您无法从 getServiceProviders
返回子节点的数量.请参阅我对此问题的回答以获得更广泛的解释:异步访问 Firebase 中的数组
Since the snapshot will be loaded asynchronously, you cannot return the number of children from getServiceProviders
. See my answer to this question for a broader explanation of that: Asynchronous access to an array in Firebase
这篇关于在 AngularFire 中使用 .numChildren()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!