我有这个代码来检查Firebase是否连接到互联网。但问题表明,即使我在construct()之前被声明为public total_downloaded=0,也无法设置我的this.total_downloaded=1。

为什么会发生这样的事情?难道我不能使用我的函数或轻松地设置变量吗?
有人能帮我吗?谢谢。下面是我的代码:
public this.total_downloaded = 0;
//...
var connectedRef = firebase.database().ref('/.info/connected');
connectedRef.once("value", function(snap) {
if (snap.val() === true) {
firebase.database()
.ref("last_update")
.once('value', (snap_0) => {
if (data.rows.item(0).value != snap_0.val().value) {
this.update_hok_baghu(db);
var query_insert_last_update = "UPDATE last_update SET value =" + snap_0.val().value + "";
db.executeSql(query_insert_last_update, []).then(() => {
}, (error) => {
console.log("ERROR on update to last_update: " + JSON.stringify(error));
});
} else {
this.total_downloaded = 1;
}
});
} else {
this.total_downloaded = 1;
}
});发布于 2017-01-16 12:23:43
您正在使用常规函数作为回调function(snap)。因此,else条件中的this引用回调函数,而不是您的类。
使用箭头函数:
connectedRef.once("value", (snap)=> {
if (snap.val() === true) {
firebase.database()
.ref("last_update")
.once('value', (snap_0) => {
if (data.rows.item(0).value != snap_0.val().value) {
this.update_hok_baghu(db);
var query_insert_last_update = "UPDATE last_update SET value =" + snap_0.val().value + "";
db.executeSql(query_insert_last_update, []).then(() => {
}, (error) => {
console.log("ERROR on update to last_update: " + JSON.stringify(error));
});
} else {
this.total_downloaded = 1;
}
});
} else {
this.total_downloaded = 1;//this will refer to class now.
}
});https://stackoverflow.com/questions/41668789
复制相似问题