Home > Blockchain >  How to Push data into Firebase Realtime database in Angular
How to Push data into Firebase Realtime database in Angular

Time:11-21

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

Firebase database snippet: enter image description here enter image description here

want to add as the first three items.

PS : data is getting added and getting successful response but is not working as expected

CodePudding user response:

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:

this.http.post('https://farmio-3lbue-default-random-rtdb.firebaseio.com/products.json' , 'Carrot')

According to the Angular docs., the HttpClient post method accepts any as the type of the body parameter.

CodePudding user response:

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:

        //            
  • Related