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;
});
this- Fiddlesbindwith an appropriate context. The issue is the observable emits a new value with each change, so your callingseteffects a change and results in the infinite loop. You could use the RxJSfirstoperator to ensure the observable emits only once and then completes, but, really, what you are doing would be better suited to using the underlying Firebase API'stransactionfunction. - cartanttransactionmethod, but this doesn't appear to be a part of AngularFire 2's wrapper API. I could use the JS SDK directly, however the current user in my system needs to be authenticated to read/write the tags. I've handled authentication using AngularFire 2. It's unclear to me how to go about using the JS SDK directly in tandem with the authentication logic from AngularFire 2. - Elliot Larson