I'm trying to get the data from my Firebase with AngularFire2. I want to check specific data and after I get this data from Firebase, I can check it only in the specific scope and not after the operation to Firebase. Why does it happen?
Below is my code:
this.af.database.list('/users/1qfcMAQnglX9jsW5GdLpPko1HqE2', { preserveSnapshot: true})
.subscribe(snapshots=>{
snapshots.forEach(snapshot => {
if(snapshot.key=="reg_boolean"){
console.log(snapshot.val());
this.bo=snapshot.val();
}
this.currentUser.push({key:snapshot.key,value:snapshot.val()});
console.log(this.currentUser);
//console.log(snapshot.key, snapshot.val());
if(this.bo==true){console.log("happy"); }; //i can access only in this scope
});
})
if(this.bo==true){console.log("happy"); }; //why i can access this value??it's undefined, this happen before the subscribe with angularfire2
It's undefined because this.af.database.list
it's asynchronous so the code in subscribe
will execute when this.af.database.list
does retrieve the data. So when the code got to the line if(this.bo==true){console.log("happy"); };
It has nothing because subscribe did not finish at all.
The subscribe it's like the old promise but now it's working with rxjs I recommend you to learn it because angular and ionic has a lot of focus on that.
Try looking at https://www.learnrxjs.io/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With