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

查看:156
本文介绍了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);
    });
  }

非常感谢您的帮助和提示:)
Luis 。

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`).$ref
    .ref.transaction(likes => {
        if (likes === null) {
            return likes = 1;
        } else {
            return likes + 1;
        }
    })
}

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

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