我正在使用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.