【问题标题】:Firebase/Angular2: How to increment a record in Firebase with AngularFire2?Firebase/Angular2:如何使用 AngularFire2 在 Firebase 中增加记录?
【发布时间】:2017-06-23 05:31:07
【问题描述】:

我想使用 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});
            }
            });          
     });

但不是只增加一次数量,而是产生一个无限循环,“数量”记录变得太大,

有帮助吗?

非常感谢,

【问题讨论】:

    标签: angular firebase firebase-realtime-database angularfire2


    【解决方案1】:

    问题是您订阅了每次值更改,这就是您进入无限循环的原因。尝试将 take(1) 添加到 subscribe 方法。

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

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

    【讨论】:

    • 感谢您的回答,但它返回错误:“订阅”类型上不存在属性“获取”
    • 尝试导入 > import 'rxjs/add/operator/take'
    • 嗨,Igor,这现在可以工作了,但有两个小改动,首先在 this.af.database.list('/products 中使用 .take(1) 或 .first() (相同含义) /'+productKey,{ preserveSnapshot: true }).take(1) (或 .first)不在最后。第二个更改是在使用上述代码之前,我们必须使用 npm i angularfire2@next --save 升级 angularFire2。谢谢你的帮助,我会接受你的回答。
    猜你喜欢
    • 2015-10-04
    • 2016-11-18
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 2017-06-03
    • 2017-06-05
    • 2018-09-03
    • 2016-11-10
    相关资源
    最近更新 更多