Return variable from firebase

Hey im trying to get the username from my firebase db and return it but all i get is “undefined”. why is that? :slight_smile:
Here is my code :

 test():string{
	var userId = firebase.auth().currentUser.uid;
	var snap;
	var ref = firebase.database().ref('users/' + userId + '/username');
	ref.on("value", function(snapshot) {
	 snap = snapshot.val();
		}, function (error) {
		console.log("Error: " + error.code);
	});
	return snap;
}
  1. It’s a lot easier to do this in AngularFire2.
  2. You are returning before the Promise resolves.
  3. To write this correctly, I recommend you get in the habit of giving every single variable a type. If you do this, you’ll notice that you’re dealing with a Promise (or really a firebase.Promise) so you can’t treat it like a synchronous variable. That will guide you to the correct solution.
1 Like

One other thing to add to @AaronSterling’s excellent post: never type the word “function” inside the body of one. Always use lambdas or arrow functions, and you will avoid 99% of common execution context loss bugs.