Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularFire2 access data after retrieve it

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

enter image description here

like image 556
Manspof Avatar asked Jan 15 '17 08:01

Manspof


1 Answers

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/

like image 56
Victor Godoy Avatar answered Oct 29 '22 03:10

Victor Godoy