AngularFire2 Access Data After Retrieval

I am trying to get data from my Firebase using AngularFire2. I want to check specific data, and after I get this data from Firebase, I can check it only in a certain area, and not after the operation with Firebase. Why is this happening?

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 undefined, this happen before the subscribe with angularfire2 

enter image description here

+5
source share
1 answer

It is undefined because this.af.database.list it is asynchronous, so the code in subscribe will be executed when this.af.database.list will retrieve the data. So, when the code hit the line if(this.bo==true){console.log("happy"); }; if(this.bo==true){console.log("happy"); }; He has nothing, because the subscription has not ended at all.

Subscribe to it as an old promise, but now it works with rxjs. I recommend that you study it, because angular and ionic pay a lot of attention to this.

Try looking at https://www.learnrxjs.io/

+8
source

Source: https://habr.com/ru/post/1262832/


All Articles