-1

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

I'm getting the following error:

TypeError: e.numChildren is not a function

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!

realph
  • 4,481
  • 13
  • 49
  • 104

1 Answers1

3

Your code snippet doesn't use AngularFire, it only uses the Firebase JavaScript SDK. Although your project undoubtedly uses AngularFire, it doesn't relate to this question.

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 is only available on a DataSnapshot object, which you get in any of the on(... event handlers.

So:

serviceProviders.on('value', function(snapshot) {
  console.log(snapshot.numChildren());
}

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

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I did initially have my `getServicesProvider` wrapped in a `$firebaseObject`, that's probably why I filed it under Angular Fire. Whats the difference between your approach, and `var getServicesProvider = $firebaseObject(ref.child('services').child(serviceId).child('providers')); getServicesProvider.$loaded().then(function(){ });` ? – realph Apr 24 '15 at 14:30
  • In general: "when you use `$loaded()` in AngularFire, you are likely doing something wrong". I had a decent discussion with Sinan about that yesterday: http://stackoverflow.com/a/29835485/209103. Also please read this section of the documentation again, as it has recently been expanded to make the asynchronous nature more clear: https://www.firebase.com/docs/web/libraries/angular/guide/intro-to-angularfire.html#section-async-intro – Frank van Puffelen Apr 24 '15 at 14:38
  • I always saw the Angular Fire API referencing `$loaded`, hence the reason I used it but thanks for this. I'll keep that in mind. – realph Apr 24 '15 at 14:48