简体   繁体   English

快照Firebase Angular之外的变量

[英]variables outside of snapshot firebase Angular

this may come across as simple but I've ran into this problem a lot with Angular and I need a little explanation. 这可能很简单,但是我在Angular遇到了很多问题,我需要一些解释。 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 谢谢

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. 这意味着javascript将调用firebase并立即调用警报功能,而无需等待任何响应。 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. 如果您使用“ this”,则在函数中访问this可能会遇到问题。 If so, change the function syntax to the arrows like this: 如果是这样,请将函数语法更改为如下所示的箭头:

testCount.on('value', (snapshot) => {

     this.testVariable = snapshot.val();


});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM