简体   繁体   English

如何在angularFire2中用已知的$ key更新记录?

[英]How to update a record with known $key in angularFire2?

I have a record in my firebase dB that I want to update. 我的Firebase dB中有一条要更新的记录。 Because I am binding the player object to UI components which I don't want to refresh before the update is submitted, I made a clone copy of the real firebase record as follows: 因为我将播放器对象绑定到不想在提交更新之前刷新的UI组件,所以我制作了真实Firebase记录的克隆副本,如下所示:

newPlayerWithSameKey(p: Player): any {
    const origKey = (<any>p).$key;
    const duplicate = JSON.parse(JSON.stringify(p))
    duplicate.$key = (<any>p).$key;
    return duplicate;
}

If I log this in the console, p and duplicate are exactly the same. 如果我在控制台中登录,则pduplicate完全相同。 The duplicate is then injected into the update method on my data service handling the records. 然后将重复项注入到处理记录的数据服务上的update方法中。 I am trying to update it this way: 我正在尝试以这种方式更新它:

updatePlayer(player: Player): void {
    const key = this.getKey(player);

    // The following three lines are just for the console log to demonstrate
    let shouldBeThePlayerToBeUpdated;
    this.db.object('/players/' + key).subscribe(p => shouldBeThePlayerToBeUpdated = p);
    window.console.log('Mock player: ', key, JSON.stringify(shouldBeThePlayerToBeUpdated));

    window.console.log('Updating player with key: ', key, JSON.stringify(player));
    this.db.list('/players').update(key, player)
}

private getKey(p: Player): string {
    return (<any>p).$key
}

But I get the following error: As you can see the keys match exactly, and the firstName property is being updated correctly (that is what I did in the form). 但是我收到以下错误:您可以看到键完全匹配,并且firstName属性正在正确更新(这就是我在表单中所做的)。 I am really confused what the problem is here ... Anybody have an idea? 我真的很困惑这里的问题是什么...有人有想法吗?

在此处输入图片说明

You can replace: 您可以替换:

this.db.list('/players').update(key, player)

by 通过

this.db.object('/players/'+key).update(player)

EDIT: 编辑:

this.db.object('/players').update({'/'+key, player})

One example of: how I use it: 一个例子:我如何使用它:

const update = {
    'starsNumber': someValue + 1
}
update[`level/${photo_id}/photo_id`] = photo_id
}

firebase
    .database()
    .ref(`game/users/${admin_id}/players/${user.id}/`)
    .update(update)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM