Trying to get child records from Firebase

前端 未结 2 1068
慢半拍i
慢半拍i 2020-12-12 03:05

Am in the angular-fire-seed tutorial stage and experimenting with messages and child posts, for some bizarre reason I cannot see the children when I explicitly try to displa

相关标签:
2条回答
  • 2020-12-12 03:21

    You seem to be falling for the common asynchonisity problem.

    This is your code fragment:

    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 
    

    The call to $asArray() doesn't return a Firebase array immediately, since the data may take some time to come down from the Firebase servers. So instead it returns the promise of a Firebase array, something that in the future will contain your data.

    By the time you inspect the out of console.log(sync) in the console, the data will have downloaded so it is (as you say) a proper synchronized array. But when the console.log(sync.length) line runs, the data probably hasn't downloaded yet.

    You can wait for the data to be downloaded with the $loaded() method. So:

    var sync = $firebase(ref).$asArray();
    
    console.log(sync);
    sync.$loaded().then(function(sync) {
      console.log(sync.length); 
      console.log(sync[1]);     
    }
    
    0 讨论(0)
  • 2020-12-12 03:28

    got the answer from AngularFire Accessing child element methods

    short answer: once assigned to a JS var, it is a POJO, not a $firebase object anymore.

    0 讨论(0)
提交回复
热议问题