Angularfire:如何将对象推入$ firebaseArray中的另一个对象?
问题描述:
我有这样的对象火力点:
Groups
-id1
name: a
-id2
name: b
-id3
name: c
我使用 “组” 是这样的:
var ref = new Firebase("https://app.firebaseio.com/Groups");
$scope.groups = $firebaseArray(ref)
$scope.groups.$add({
"name": "d"
}).then(function (ref)
{
console.log('Added group');
}, function (error)
{
console.error("Error:", error);
});
一些团体包含的项目。我如何添加一个数组并在其中推入一些项目?如何处理数组已经存在的情况?
这不起作用:
var group = Groups.$getRecord(id3)
if(!group.hasOwnProperty('items')){
group['items'] = []
}
group['items'].push({item: "an item"})
答
一般来说,avoid nested arrays和flatten data在可能的情况。
如果这些项目被多个用户异步更新,您将会有冲突和奇怪的行为,因为arrays in distributed data杀死了小猫。
直接在项目创建阵列添加和使用推ID,而不是:
var ref = new Firebase("https://app.firebaseio.com/Groups/d/items");
$scope.items = $firebaseArray(ref)
$scope.items.$add({ $value: "an item" });
或者,如果我们要在groups
同步真想每次更改每一次每一组同步,那么这会更简单和更好:
new Firebase("https://app.firebaseio.com/Groups/d/items").push("an item");
+0
谢谢@Kato!我正在构建一款将在单个设备上使用的应用程序,这就是为什么我不关心并发操作的原因。 :) – Alain1405
什么是'组。$ getRecord(id3)'? 'group。$ push()'相同,因为afaik AngularFire没有'$ push()'方法。 –
我使用getRecord来获取包含组数据的对象。我编辑了这个问题,使之更加清晰。 – Alain1405