我正在使用 Angular 2 和 AngularFire 2 与 Firebase 交互。在 Firebase 中,我有一个标签集合。我想创建或增加标签的数字。我使用的代码看起来像这样:
let tagName = "angular";
let tagObs = this.af.database.object(`/tags/${tagName}`);
tagObs.subscribe(function(snapshot) {
let newValue = (snapshot.$value) ? (snapshot.$value + 1) : 1;
this.tagObs.set(newValue);
}.bind({ tagObs: tagObs ));
我不清楚为什么,但这行不通。它会创建一个无限循环,不断递增标签值。
使用 AngularFire 2,我应该如何为节点(在本例中为“标签”)创建或增加值?
@Fiddle 评论后更新
这是带有“粗箭头”功能的相同代码。存在同样的问题……无限循环。
let tagName = "angular";
let tagObs = this.af.database.object(`/tags/${tagName}`);
tagObs.subscribe((snapshot) => {
let newValue = (snapshot.$value) ? (snapshot.$value + 1) : 1;
tagObs.set(newValue);
});
更新 #2:有效的代码
为了清楚起见,这是我最终使用的实际代码:
let tagObs = this.af.database.object(`/tags/${tagName}`);
tagObs.transaction(function(currentCount) {
return currentCount + 1;
});
最佳答案
无限循环
你得到了一个无限循环,因为每次 tagObs
引用接收到新值时都会调用 subscribe
方法,并且 subscribe 函数会更改 tabObs 的值
使用 set
方法。
Firebase 交易
Firebase 提供了一个 transaction这种情况的方法。这真的很有帮助,因为:
transaction()
is used to modify the existing value to a new value, ensuring there are no conflicts with other clients writing to the same location at the same time.
tagObs.$ref.transaction(tagValue => {
return tagValue ? tagValue + 1 : 1;
});
请务必注意,这是来自 Firebase API(而非 Angularfire2)的方法,但您仍然可以通过在提供的 tagObs
上调用 $ref
来访问这些方法它看起来像一个 FirebaseObjectObservable
。
关于angular - 使用 Angular2/AngularFire2 创建或增加一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40795605/