加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用Angular2 / AngularFire2创建或增加值

发布时间:2020-12-17 17:32:06 所属栏目:安全 来源:网络整理
导读:我正在使用Angular 2和AngularFire 2与Firebase进行交互.在Firebase中,我有一个标签集合.我想创建或增加标签的数量.我正在使用的代码看起来像这样: let tagName = "angular";let tagObs = this.af.database.object(`/tags/${tagName}`);tagObs.subscribe(fu
我正在使用Angular 2和AngularFire 2与Firebase进行交互.在Firebase中,我有一个标签集合.我想创建或增加标签的数量.我正在使用的代码看起来像这样:

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

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

使用AngularFire 2,我应该如何创建或增加节点的值(在这种情况下为“标签”)?

@Fiddle评论后更新

这是具有“胖箭头”功能的相同代码.存在同样的问题……无限循环.

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:有效的代码

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

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

解决方法

无限循环

您有一个无限循环,因为每次tagObsreference接收到一个新值时都会调用subscribe方法,而subscribe函数会使用set方法更改tabObs的值.

Firebase交易

Firebase为此情况提供了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来访问这些方法,这些tagObs看起来像FirebaSEObjectObservable.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读