angularfire2增加值的最佳方法?
发布时间:2020-12-17 06:56:48 所属栏目:安全 来源:网络整理
导读:我在 doc搜索了许多论坛,问题,但无法找到正确的解决方案. 问题 使用angularfire2增加值的最佳方法是什么? 我看到我们可以使用[transaction()] []但实际上并不适用于angularfire2. 还是快照? user.service.ts incrementLike(userToIncrementLike){ this.af.
我在
doc搜索了许多论坛,问题,但无法找到正确的解决方案.
问题 使用angularfire2增加值的最佳方法是什么? user.service.ts incrementLike(userToIncrementLike){ this.af.database.object('users/' + userToIncrementLike.uid).subscribe((userObject) => { var newUser = { likes: userObject.likes + 1 }; }); this.af.database.object('users/' + userToIncrementLike.uid).update(newUser); } 我也试过这种方式: incrementLike(userToIncrementLike){ let obs = this.af.database.object('users/' + userToIncrementLike.uid); obs.subscribe((snapshot) => { let newValue = (snapshot.$value) ? (snapshot.$value + 1) : 1; obs.set(newValue); }); } 非常感谢您的帮助和提示:) 解决方法
没有必要定义对象或使用update()方法.该对象已存在于数据库中,因此您可以在其中进行处理.这实际上是transaction() –
to work on the data at the data location的目的,因此可以防止冲突;例如,两个用户同时更新相同的值.
如果您愿意,也可以在路径中使用模板文字. :)(注意反引号而不是单引号.) incrementLike(userToIncrementLike){ this.af.database.object(`users/${userToIncrementLike.uid}/likes`).$ref .ref.transaction(likes => { if (likes === null) { return likes = 1; } else { return likes + 1; } }) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |