简体   繁体   English

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

[英]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.

相关问题 Angular2和Firebase(AngularFire2) - Angular2 and Firebase (AngularFire2) Angular2、Firebase、AngularFire2、路由守卫以及如何处理订阅 - Angular2, Firebase, AngularFire2, route guard and how to deal with subscription angular2和firebase与angularfire2如何在打字稿中的列表上进行迭代 - angular2 and firebase with angularfire2 how to iterate over list in typescript 使用Angular2,angularfire2和Typescript从Firebase对象中获取数据 - Getting Data out of Firebase Object with Angular2, angularfire2 and Typescript 使用AngularFire2访问firebase.storage()(Angular2 rc.5) - Accessing firebase.storage() with AngularFire2 (Angular2 rc.5) 使用Angular2 / AngularFire2创建或增加值 - Create or increment a value with Angular2/AngularFire2 如何在 Angular2 服务中注入 FirebaseApp 以将 firebase.storage() 与 AngularFire2 一起使用 - How to inject FirebaseApp in Angular2 service to use firebase.storage() with AngularFire2 Angular2与angularfire2 - Angular2 with angularfire2 Firebase查询返回{$ value:null},其中有一个数组-Ionic / Angular2 / AngularFire2 - Firebase query returns {$value:null} where there is an array - Ionic/Angular2/AngularFire2 使用AngularFire2 @ angular / fire V5在Firebase文档中增加一个值 - Increment a value inside Firebase document using AngularFire2 @angular/fire V5
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM