angularfire2 增加值的最佳方法? [英] angularfire2 best way to increment a value?

查看:42
本文介绍了angularfire2 增加值的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在许多论坛、问题、doc 中搜索,但找不到正确的解决方案.

I searched in many forums, questions, in doc but can't find the correct solution.

使用 angularfire2 增加值的最佳方法是什么?
我看到我们可以使用 [transaction()][] 但它实际上不适用于 angularfire2.还是使用快照?

What is the best way to increment a value using angularfire2 ?
I saw we could use [transaction()][] but it's not for angularfire2 actually. Or with snapshot ?

user.service.ts

user.service.ts

incrementLike(userToIncrementLike){
    this.af.database.object('users/' + userToIncrementLike.uid).subscribe((userObject) => {
      var newUser = {
        likes: userObject.likes + 1
        };

     });
     this.af.database.object('users/' + userToIncrementLike.uid).update(newUser);

  }

我也试过这种方式:

incrementLike(userToIncrementLike){

    let obs = this.af.database.object('users/' + userToIncrementLike.uid);
    obs.subscribe((snapshot) => {
      let newValue = (snapshot.$value) ? (snapshot.$value + 1) : 1;
      obs.set(newValue);
    });
  }

非常感谢您的帮助和提示:)路易斯.

Thank you very much for your help and tips :) Luis.

推荐答案

不需要定义对象或使用 update() 方法.该对象已存在于数据库中,因此您可以在那里对其进行处理.这实际上是 transaction()--在数据位置处理数据,从而防止冲突;例如,两个用户同时更新相同的值.

It isn't necessary to define an object or to use the update() method. The object already exists in the database, so you can just work on it there. This is actually the purpose of transaction()--to work on the data at the data location and therefore prevent conflicts; e.g., two users updating the same value at the same time.

如果愿意,您也可以在路径中使用模板文字.:)(注意反引号而不是单引号.)

You can also use the template literal in your path if you like. :) (Note the backticks instead of single quotes.)

incrementLike(userToIncrementLike){
    this.af.database.object(`users/${userToIncrementLike.uid}/likes`).query
    .ref.transaction(likes => {
        if (likes === null) {
            return likes = 1;
        } else {
            return likes + 1;
        }
    })
}

更新:2019 年 9 月.使用 query 而不是 $ref.

Update: September, 2019. Use query instead of $ref.

这篇关于angularfire2 增加值的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆