Firebase实时数据库设置来自addeventlistner的字段

kkbh8khc  于 2023-04-07  发布在  其他
关注(0)|答案(1)|浏览(98)

我是Web开发的新手,我正试图用Firebase构建一个简单的Web应用程序。
我的问题是,如果我写下面的addeventlistner,我看到警报,但没有添加到数据库,但如果我写相同的代码行在全局范围内的字段被添加。

**This is not working:**

import { initializeApp } from 'firebase/app';
import { getDatabase, ref, set } from 'firebase/database';

const firebaseConfig = {
    blablabla
};

const firebaseApp = initializeApp(firebaseConfig);
const db = getDatabase(firebaseApp);

document.getElementById("addBtn").addEventListener("click", function() {
    alert("test");
    let field1 = "10";
    let field2 = "10";
    let date = "2023-04-10";

    set(ref(db, 'score/' + date), {
        "field_1": field1,
        "field_2": field2
    });
    
});

**this is working:**
import { initializeApp } from 'firebase/app';
import { getDatabase, ref, set } from 'firebase/database';

const firebaseConfig = {
    blablabla
};

const firebaseApp = initializeApp(firebaseConfig);
const db = getDatabase(firebaseApp);
    let field1 = "10";
    let field2 = "10";
    let date = "2023-04-10";

    set(ref(db, 'score/' + date), {
        "field_1": field1,
        "field_2": field2
    });
fykwrbwg

fykwrbwg1#

您可以尝试将代码 Package 在函数中,然后在事件侦听器函数中调用该函数。例如:

import { initializeApp } from 'firebase/app';
import { getDatabase, ref, set } from 'firebase/database';

const firebaseConfig = {
    // Your Firebase config here
};

const firebaseApp = initializeApp(firebaseConfig);
const db = getDatabase(firebaseApp);

function addToDatabase() {
    let field1 = "10";
    let field2 = "10";
    let date = "2023-04-10";

    set(ref(db, 'score/' + date), {
        "field_1": field1,
        "field_2": field2
    });
}

document.getElementById("addBtn").addEventListener("click", function() {
    alert("test");
    addToDatabase();
});
// Or
document.getElementById("addBtn").addEventListener("click", () => {
    alert("test");
    addToDatabase();
});

建议

要解决这类问题,我建议在set()方法中添加错误处理,以查看它是否抛出任何错误。您可以通过在set()方法中添加第二个参数来做到这一点,这是一个回调函数,如果有错误,将使用错误对象调用。
下面是一个例子:

set(ref(db, 'score/' + date), {
    "field_1": field1,
    "field_2": field2
}, function(error) {
    if (error) {
        console.log("Error adding data to database:", error);
    } else {
        console.log("Data added to database successfully");
    }
});

相关问题