angularjs - Asynchronous access to an array in Firebase -


here code:

var userref = new firebase("https://awesome.firebaseio.com/users/");  var tokenref = userref.child(key+'/tokens'); tokenref.once('value', function(snapshot){    var usertokensync = $firebase(tokenref);   var usertokens = usertokensync.$asarray();     console.log(usertokens);   console.log(usertokens[0]);    for(var i=0, len = usertokens.length; < len; i++) {      console.log(usertokens[i]);   }   console.log('done'); }) 

this code gets tokens of user firebase, , want browse tokens array.

here console gives me:

enter image description here

as can see, cannot access array. have idea of how this?

thanks in advance.

welcome asynchronous loading 101.

  var usertokens = usertokensync.$asarray();    console.log(usertokens);   console.log(usertokens[0]);    for(var i=0, len = usertokens.length; < len; i++) {      console.log(usertokens[i]);   }   console.log('done'); 

the first line of snippets starts loading data firebase. loading might take time. , since browser doesn't want block things, continues executing script.

by time browser executes console.log(usertokens); data hasn't been loaded yet. prints object console placeholder.

by time gets for loop, data may or may not yet have been loaded firebase.

at point clicked arrow next logged usertokens. time data had loaded firebase , console shows latest data.

the solution provided angularfire, in form of promise. angularfire promises @ point in future have data you. if have piece of code should execute when data loaded, can write this:

  var usertokens = usertokensync.$asarray();    console.log(usertokens);   console.log(usertokens[0]);    usertokens.$loaded(function(usertokens) {     for(var i=0, len = usertokens.length; < len; i++) {       console.log(usertokens[i]);     }     console.log('done');   });    console.log('at last line, not done yet'); 

update

note above bad example of when use $loaded. since $loaded fire once, log initial contents of array. if you're trying see if/when data has loaded, idiomatic approach add usertokens scope:

$scope.usertokens = usertokens; 

and add view/html:

<pre>{{ usertokens | json }}</pre> 

angularfire monitor when usertokens loaded or modified in way , tell angularjs update view if happens.

also see these:

yup... question lot.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -