这个问题在这里已有答案:
我写了一个函数来检查我的firebase数据库中的“phonenumber”子项中是否有数据保存..测试是OKEY!但在这个函数里面我不能调用外部声明的变量!这是代码:
phoneNumberExistence: boolean;
FIREBASE_DATABASE.ref("Settings").child('phoneNumber').once('value', function(snapshot) {
var exists = (snapshot.val() !== null);
//console.log("Phone number existance: "+exists);
if(exists){
this.phoneNumberExistence = true; //the problem is here.. can't use this variable
console.log("A phone number already exists.")
}
else{
this.phoneNumberExistence = false; //the problem is here.. can't use this variable
console.log("There is no phone number here :(");
}
})
任何的想法 ?谢谢
使用箭头函数而不是function(snapshot) {...}
... .once('value', (snapshot) => {
var exists = (snapshot.val() !== null);
...
});
箭头函数在词法上绑定它们的上下文,因此这实际上是指原始上下文。有关更多详细信息,请阅读this article。