【问题标题】:Cannot set property 'variable' of null on Firebase无法在 Firebase 上设置属性“变量”为 null
【发布时间】:2017-05-30 20:13:52
【问题描述】:

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

为什么会这样?我不应该能够轻松使用我的函数或设置变量吗?

有人可以帮助我吗?谢谢。这是我的代码:

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;
    }
});

【问题讨论】:

    标签: typescript firebase ionic-framework firebase-realtime-database ionic2


    【解决方案1】:

    您正在使用常规函数作为回调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.
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 2013-04-21
      • 2013-08-16
      • 2017-05-05
      • 2021-10-28
      • 2021-05-30
      • 2021-10-02
      相关资源
      最近更新 更多