javascript - how can I store a firebase query object in a variable in angular? -


i trying make query firebase database using ionic. want store the object snapshot.val() in variable objective of displaying content in html code i´m struggling scope of upcomingorders variable.

how can update variable inside callback?

  onfetchmyupcomingorders(){     var upcomingorders = {}     const userid = this.authservice.getactiveuser().uid;     var ref = firebase.database().ref("orders/confirmed");     ref.orderbychild("client/clientid").equalto(userid).once("value", (snapshot) => {         upcomingorders= snapshot.val()         console.log(upcomingorders)       });     console.log(upcomingorders) // empty object, should contain snapshot.val()   }   

it seems it's updating value. how can update reference?

the data loaded firebase asynchronously. while data being loaded, function continues run. when console.log() before end of function executes, data hasn't been loaded yet. when data becomes available, callback function invoked.

so: upcomingorders variable is being set correctly, not @ moment want it.

to make code work, must move code needs data into callback function. if want update html, inside callback:

onfetchmyupcomingorders(){   var upcomingorders = {}   const userid = this.authservice.getactiveuser().uid;   var ref = firebase.database().ref("orders/confirmed");   ref.orderbychild("client/clientid").equalto(userid).once("value", (snapshot) => {     upcomingorders= snapshot.val()     // todo: update html , whatever else needs data   }); } 

this extremely common pattern when using modern web apis. data loaded asynchronously time, , callback such (or more modern equivalent such promise or async/await) way deal it.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -