【发布时间】:2021-10-28 14:33:37
【问题描述】:
我目前正在开发一个显示“开始”按钮的程序。一旦用户点击这个按钮,它就会消失并且会:
- 将
playerCount设置为1(如果playerCount不存在) - 或将
playerCount增加1。
我主要是在将 playerCount 增加 1 时遇到问题。我一直在关注 Atomic server-side increments 的 Firebase 文档。网页和“开始”按钮都会出现。但是,单击按钮并消失后,我收到错误消息:
TypeError: Cannot read properties of undefined (reading 'ServerValue') at [localhost url].js:37:65 {stack: "TypeError: Cannot read properties of undefined (re…ost:[localhost url].js:37:65", message: "Cannot read properties of undefined (reading 'ServerValue')"}.
有一个类似的帖子(但这是针对 FireBase Cloud)firebase cloud function ServerValue increment not working。我曾尝试使用admin 而不是firebase,但最终得到Error 404 错误。
如果这有帮助,这是我的game.js:
import * as firebase from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
import { set, ref, getDatabase, child, get } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-database.js';
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "apiKey information",
authDomain: "authDomain information",
databaseURL: "databaseURL information",
projectId: "projectId information",
storageBucket: "storageBucket information",
messagingSenderId: "messagingSenderId information",
appId: "appId information",
measurementId: "measurementId information"
};
const app = firebase.initializeApp(firebaseConfig);
const database = getDatabase(app);
function setPlayerCount() {
const dbRef = ref(getDatabase());
get(child(dbRef, 'game/')).then((snapshot) => {
if (snapshot.exists()) {
const updates = {};
updates['game/playerCount'] = firebase.database.ServerValue.increment(1);
database().ref().update(updates);
}
else {
set(ref(database, 'game/'), {
playerCount: 1
})
}
}).catch((error) => {
console.error(error);
})
}
// Display Start Button and increment player count
let button = document.createElement('button');
button.innerHTML = "Start";
button.onclick = function () {
setPlayerCount();
button.style.display = "none";
}
document.body.appendChild(button);
还有我的 index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script defer type="module" src="game.js"></script>
<style type="text/css">
body {
margin: 0;
}
</style>
</head>
<body>
</body>
</html>
非常感谢任何帮助!
【问题讨论】:
标签: javascript firebase firebase-realtime-database