Reputation: 381
I want to increment a record in firebase using AngularFire2, below is my method:
const productsQuery = this.af.database.list('/products/'+productKey,{ preserveSnapshot: true });
const productUpdate = this.af.database.list('/products');
productsQuery.subscribe(snapshots => {
snapshots.forEach(snapshot => {
if (snapshot.key == "quantity") {
productUpdate.update(productKey,{quantity: snapshot.val()+1});
}
});
});
But instead of incrimenting quantity just one time, this produces an infinite loop and the "quantity" record becomes too big,
any help guys?
Thanks a lot,
Upvotes: 0
Views: 441
Reputation: 5532
The problem is that you are subscribed on every value change and that is the reason why you are getting in the infinite loop. Try adding take(1) to the subscribe method.
const productsQuery = this.af.database.list('/products/'+productKey,{ preserveSnapshot: true });
const productUpdate = this.af.database.list('/products');
productsQuery.subscribe(snapshots => {
snapshots.forEach(snapshot => {
if (snapshot.key == "quantity") {
productUpdate.update(productKey,{quantity: snapshot.val()+1});
}
});
}).take(1);
In this case, it should take the value only once.
Upvotes: 3