问题
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.
Using AngularFire 2, how should I go about either creating or incrementing a value for a node (a "tag" in this case)?
Update after @Fiddle's comment
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
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;
});
回答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.
Firebase Transactions
Firebase provides a transaction method for this situation. 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.
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
.
来源:https://stackoverflow.com/questions/40795605/create-or-increment-a-value-with-angular2-angularfire2