使用 Angular2/AngularFire2 创建或增加一个值 [英] Create or increment a value with Angular2/AngularFire2

查看:27
本文介绍了使用 Angular2/AngularFire2 创建或增加一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Angular 2 和 AngularFire 2 与 Firebase 交互.在 Firebase 中,我有一个标签集合.我想创建或增加标签的编号.我使用的代码如下所示:

I'm using Angular 2 and AngularFire 2 to interact with Firebase. In Firebase I have a tags collection. I'd like to either create or increment the number for a tag. The code I'm using looks something like this:

let tagName = "angular";
let tagObs = this.af.database.object(`/tags/${tagName}`);
tagObs.subscribe(function(snapshot) {
    let newValue = (snapshot.$value) ? (snapshot.$value + 1) : 1;
    this.tagObs.set(newValue);
}.bind({ tagObs: tagObs ));

我不清楚为什么,但这不起作用.它创建了一个无限循环,不断增加标签值.

It's not clear to me why, but this doesn't work. It creates an infinite loop that just keeps incrementing the tag value.

使用 AngularFire 2,我应该如何为节点(在本例中为标签")创建或增加值?

Using AngularFire 2, how should I go about either creating or incrementing a value for a node (a "tag" in this case)?

这是带有粗箭头"功能的相同代码.同样的问题存在......无限循环.

Here is the same code with a "fat arrow" function. The same problem exists... an infinite loop.

let tagName = "angular";
let tagObs = this.af.database.object(`/tags/${tagName}`);
tagObs.subscribe((snapshot) => {
    let newValue = (snapshot.$value) ? (snapshot.$value + 1) : 1;
    tagObs.set(newValue);
});

更新#2:有效的代码

为了清楚起见,这是我最终使用的实际代码:

Update # 2: the code that worked

Just for the sake of clarity, this is the actual code I ended up using:

let tagObs = this.af.database.object(`/tags/${tagName}`);
tagObs.transaction(function(currentCount) {
  return currentCount + 1;
});

推荐答案

无限循环

你有一个无限循环,因为每次 tagObs 引用收到一个新值时都会调用 subscribe 方法,而 subscribe 函数改变了 tabObs 的值 使用 set 方法.

Infinite loop

You got an infinite loop because the subscribe method is called every time the tagObsreference receives a new value, and the subscribe function changes the value of tabObs with the set method.

Firebase 为这种情况提供了一个 transaction 方法.这真的很有帮助,因为:

Firebase provides a transaction method for this situation. This is really helpful because:

transaction() 用于将现有值修改为新值,确保不会与同时写入同一位置的其他客户端发生冲突.

transaction() is used to modify the existing value to a new value, ensuring there are no conflicts with other clients writing to the same location at the same time.

tagObs.$ref.transaction(tagValue => {
  return tagValue ? tagValue + 1 : 1;
});

请务必注意,这是来自 Firebase API(不是 Angularfire2)的方法,但您仍然可以通过在提供的 tagObs 上调用 $ref 来访问这些方法它看起来像一个 FirebaseObjectObservable.

It's important to note that this is a method from the Firebase API (not Angularfire2), but you can still access those methods by calling $ref on your provided tagObs which looks like a FirebaseObjectObservable.

这篇关于使用 Angular2/AngularFire2 创建或增加一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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