Cannot set property 'variable' of null on

2019-08-01 13:14发布

问题:

I have this code to check either the Firebase connected to the internet or not. But the problem shows that my this.total_downloaded=1 cannot be set even I was declared before construct() as public total_downloaded=0.

Why does it happen like that? Shouldn't I be able to use my function or set the variable easily?

Can someone help me? Thanks. Here's my code:

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

回答1:

You are using the regular function as callback function(snap). So the this in your else condition refers to the callback function and not your class.

Use arrow function:

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