I’m just starting out with angualar and wanted to push data into Firebase Database in angular , currently using post for that but some random data is getting appended into the database.
The code is as follows:
Angular was giving error when not specifying the key , so gave ‘value’
this.http.post('https://farmio-3lbue-default-random-rtdb.firebaseio.com/products.json' , { 'value' : 'Carrot'}).subscribe(res=>{
console.log(res , 'post')
}, error=> console.log(error))
want to add as the first three items.
PS : data is getting added and getting successful response but is not working as expected
2
Answers
Your "products" entity is a JS
Array
. Which means that you can’t refer it as a key-value object but as an array with index.Once you pushed a new object
{ 'value' : 'Carrot'}
into your array, the whole object was saved into the array. Instead, it seeme that what you want is to save the'Carrot'
string only.What you have to do is to send the literal string itself in the body:
According to the Angular docs., the
HttpClient
post
method acceptsany
as the type of the body parameter.I recommend first reading this article to gain an understanding how Firebase handles arrays: Best Practices: Arrays in Firebase.
When you
POST
data to the REST API of the Firebase Realtime Database, it auto-generates a so-called key for that data of the-N....
format that you see. That’s the only format it uses for adding data to a list, for reasons explained in the article I linked.If you want to add an item to the array, you will have to specify the index/key of that item yourself and use a
PUT
command:This means that you must somehow already know how many items there are in the database already, which may require you to read the data before you can add the item – something which in turns means that you should use a transaction for the operation.
All good reasons to not use sequential numeric keys in the database, but instead rely on the push keys that it offers as a built-in primitive.