Marian07 Marian07 - 3 months ago 64
JSON Question

Angularfire2 - append item directly to list

When I

push("number")
into firebase, with angularfire2, the number isn't appended directly, instead it's nested inside a generated code.

Inside Firebase Realtime Database:

1) Initial code:



"myList": {
"0": {
"key1": "val1"
},
"1": {
"key2": "val2"
}
}


2) After
.push({"key3": "val3"})


"myList": {
"0": {
"key1": "val1"
},
"1": {
"key2": "val2"
},
"-generatedcode_": {
"key3": "val3"
}
}


Why the new object was not added directly, without nesting?

Answer

What you are seeing is the expected behaviour. The push function on AngularFire2's FirebaseListObservable uses the underlying Firebase API's push, which generates a unique, sortable key:

The unique key generated by push() are ordered by the current time, so the resulting list of items will be chronologically sorted. The keys are also designed to be unguessable (they contain 72 random bits of entropy).

push generates a unique key so that so that it's safe for multiple users to be pushing data into the one location. If that is not a problem and you wish to create a "2" key, you can do so, but you cannot do it using the FirebaseListObservable. You could use the underlying Firebase API:

firebase.database().ref("/myList/2").set({ "key3": "val3" });

Or you could use an AngularFire2 FirebaseObjectObservable:

let o = af.database.object("/myList/2");
o.set({ "key3": "val3" });

Where af is your AngularFire instance.

After performing either set, you should see your FirebaseListObservable instance updated to include the newly added data.

Comments