I'm new in Firebase and Typrescript. I have the following problem: I want the username of a user from the realtime database.
  getUsername(id){
    var username
    firebase.database().ref().child("users/"+id+"/username")
    .once("value",snapshot => {
      if (snapshot.exists()){
        username = snapshot.val();
        console.log("IN"+username)      
      }
    });
    console.log("OUT"+username)
    return username
  }
The problem is that outside the if() the username is undefined. I read that with firebase you have to work asynchronously, so I followed this guide: How do I return a snapshot.val() from Firebase to a variable? so I created the functions:
   getListings(id) {
    return firebase.database().ref().child("users/"+id+"/username").once("value");
  }
  
   loadListing(id){
    this.getListings(id).then(this. setListing, this.showError);
}
   setListing(snapshot){
      this.currentSnapshot = snapshot.val()
  }
  
   showError(e){
      console.log(e);
  }
  
   init(id){
      this.loadListing(id);
  }
and in other page I call init:
export class ProfilePage implements OnInit {
  username : any;
  constructor(private route: ActivatedRoute, private router: Router, public authService: AuthenticationService) {};
  
  ngOnInit() {
    this.authService.init(this.authService.userData.uid)
    console.log(this.authService.currentSnapshot)
  }
}
but i receive the error:
Error: Uncaught (in promise): TypeError: Cannot set property 'currentSnapshot' of undefined
Can anyone help me ?
 
    