variables outside of snapshot firebase Angular

Home / Uncategorized / variables outside of snapshot firebase Angular

Question:
this may come across as simple but I’ve ran into this problem a lot with Angular and I need a little explanation. All I’m trying to do is get a variable value outside of the snapshot function. If I could do something like this
let testVariable : string;

var testCount = firebase.database().ref(‘users/’ + userName + ‘/userName’);

testCount.on(‘value’, function (snapshot) {

testVariable = snapshot.val();

});

alert(testVariable); //comes out undefined

Thank you


Answer:
The problem is your code is running asynchronously. This means that javascript will make the call to firebase and immediately call the alert function, without waiting for any response. Your alert must either be placed in a callback or called after the variable has been set.

If you are using "this" you might have problems accessing this within the function. If so, change the function syntax to the arrows like this:testCount.on(‘value’, (snapshot) => {

this.testVariable = snapshot.val();

});
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *