简体   繁体   English

使用Angular2 / AngularFire2创建或增加值

[英]Create or increment a value with Angular2/AngularFire2

I'm using Angular 2 and AngularFire 2 to interact with Firebase. 我正在使用Angular 2和AngularFire 2与Firebase进行交互。 In Firebase I have a tags collection. 在Firebase中,我有一个标签集合。 I'd like to either create or increment the number for a tag. 我想创建或增加标签的数量。 The code I'm using looks something like this: 我正在使用的代码看起来像这样:

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 ));

It's not clear to me why, but this doesn't work. 我不清楚为什么,但这不起作用。 It creates an infinite loop that just keeps incrementing the tag value. 它创建了一个无限循环,只是不断增加标记值。

Using AngularFire 2, how should I go about either creating or incrementing a value for a node (a "tag" in this case)? 使用AngularFire 2,我应该如何创建或增加节点的值(在这种情况下为“标签”)?

Update after @Fiddle's comment @Fiddle评论后更新

Here is the same code with a "fat arrow" function. 这是具有“胖箭头”功能的相同代码。 The same problem exists... an infinite loop. 存在同样的问题......无限循环。

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);
});

Update # 2: the code that worked 更新#2:有效的代码

Just for the sake of clarity, this is the actual code I ended up using: 为了清楚起见,这是我最终使用的实际代码:

let tagObs = this.af.database.object(`/tags/${tagName}`);
tagObs.transaction(function(currentCount) {
  return currentCount + 1;
});

Infinite loop 无限循环

You got an infinite loop because the subscribe method is called every time the tagObs reference receives a new value, and the subscribe function changes the value of tabObs with the set method. 您有一个无限循环,因为每次tagObs引用接收到一个新值时都会调用subscribe方法,而subscribe函数会使用set方法更改tabObs的值。

Firebase Transactions Firebase交易

Firebase provides a transaction method for this situation. Firebase为此情况提供了一种事务处理方法。 This is really helpful because: 这非常有用,因为:

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. transaction()用于将现有值修改为新值,确保与同时写入同一位置的其他客户端不冲突。

tagObs.$ref.transaction(tagValue => {
  return tagValue ? tagValue + 1 : 1;
});

It's important to note that this is a method from the Firebase API (not Angularfire2), but you can still access those methods by calling $ref on your provided tagObs which looks like a FirebaseObjectObservable . 重要的是要注意这是来自Firebase API(而不是Angularfire2)的方法,但您仍然可以通过在提供的tagObs上调用$ref来访问这些方法,这些tagObs看起来像FirebaseObjectObservable

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

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