使用Angular2/AngularFire2创建或增加值 [英] Create or increment a value with Angular2/AngularFire2
问题描述
我正在使用Angular 2和AngularFire 2与Firebase进行交互.在Firebase中,我有一个标签集合.我想为标签创建或增加编号.我正在使用的代码如下所示:
I'm using Angular 2 and AngularFire 2 to interact with Firebase. In Firebase I have a tags collection. 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.
使用AngularFire 2,我应该如何为节点创建或增加一个值(在这种情况下为标签")?
Using AngularFire 2, how should I go about either creating or incrementing a value for a node (a "tag" in this case)?
这是带有胖箭头"功能的相同代码.存在相同的问题...无限循环.
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);
});
更新#2:有效的代码
为了清楚起见,这是我最终使用的实际代码:
Update # 2: the code that worked
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;
});
推荐答案
无限循环
您遇到了无限循环,因为每次tagObs
引用接收到新值时都会调用subscribe
方法,并且subscription函数使用set
方法更改tabObs
的值.
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.
Firebase针对这种情况提供了事务方法.这真的很有帮助,因为:
Firebase provides a transaction method for this situation. This is really helpful because:
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
.
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
.
这篇关于使用Angular2/AngularFire2创建或增加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!