使用 Angular2/AngularFire2 创建或增加一个值

Create or increment a value with Angular2/AngularFire2

我正在使用 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,我应该如何为节点(在本例中为 "tag")创建或增加值?

@Fiddle评论后更新

下面是带有 "fat arrow" 函数的相同代码。同样的问题存在...死循环。

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 方法,并且订阅函数会使用 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)的方法,但您仍然可以通过调用 $ref 来访问这些方法 tagObs看起来像 FirebaseObjectObservable.