[英]Firebase/Angular2: How to increment a record in Firebase with AngularFire2?
I want to increment a record in firebase using AngularFire2, below is my method: 我想使用AngularFire2在firebase中增加一条记录,以下是我的方法:
const productsQuerry = this.af.database.list('/products/'+productKey,{ preserveSnapshot: true });
const productUpdate = this.af.database.list('/products');
productsQuerry.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, 非常感谢,
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.
尝试将take(1)添加到订阅方法。
const productsQuerry = this.af.database.list('/products/'+productKey,{ preserveSnapshot: true });
const productUpdate = this.af.database.list('/products');
productsQuerry.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. 在这种情况下,该值只能取一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.