Firebase/Angular2: 如何使用 AngularFire2 在 Firebase 中增加记录?

Firebase/Angular2: How to increment a record in Firebase with AngularFire2?

我想使用 AngularFire2 在 firebase 中增加一条记录,下面是我的方法:

     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) 添加到订阅方法中。

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);

在这种情况下,它应该只取值一次。