当比赛的主机创建一个新的游戏时,我试图存储游戏设置。他们只有一次机会改变设置,然后它就会锁定。
我的问题是,我无法弄清楚如何从firebase获取匹配设置/锁定索引的索引值(它应该是true或false)。
该方法工作正常,但我现在要停止播放机在第一次方法调用后编辑设置。
changeSettings(time, increment) : void {
let timePerRound = time;
let decrease= increment;
this.db.database.ref(`users/${this.gameId}/matchSettings/locked`).once('value').then( s => {
if (s == true) {
// dont allow another update
}
})
this.db.object(`games/${this.gameId}/matchSettings`).update({
timePerRound: time, decrease: increment, locked: true
});
console.log("game settings updated")
}这里有一些显示数据库的打印脚本.
http://prntscr.com/n0n9ef <-数据未被锁定,因此允许更改一次设置。http://prntscr.com/n0n9ov <--我现在调用了changeSettings(45,45),但是它也会将锁更改为= true。
发布于 2019-03-20 21:29:16
首先,您面临的一个问题是,您的第一个数据库引用是针对users的,而它应该是针对games的。除此之外..。
应该将更新调用移到从数据库接收的第一个结果中,以便知道是否允许更新:
changeSettings(time, increment) : void {
let timePerRound = time;
let decrease= increment;
this.db.database.ref(`games/${this.gameId}/matchSettings/locked`).once('value')
.then( s => {
if (s == true) {
// dont allow another update
} else {
// Yes allow the update
this.db.object(`games/${this.gameId}/matchSettings`).update({
timePerRound: time, decrease: increment, locked: true
});
console.log("game settings updated")
}
})
}当然,这段代码是可以优化的,这是一个非常难看的if/else语句.但是,为了理解,让我们把它放在基本的位置。
请注意,这是不够的,并不是真的。这只是前端的保安..。这是幻觉。如果你真的想阻止游戏设置的改变,那么你应该实现数据库规则的效果。例如,类似于:
{
"rules": {
"games": {
"$gameId": {
"matchSettings": {
// Allow writing to this node only if...
// If the old data doesn't exist... (allow create attempts)
// Or if the old data's "locked" property is false
".write": "!data.exists() || data.child('locked').val() == false"
}
}
}
}
}*免责声明:未经测试的代码和规则,例如仅限
https://stackoverflow.com/questions/55268441
复制相似问题