Vik
Vik

Reputation: 9319

Parsing json response gives undefined

I am using angularfire2 to fetch data from realtime DB. and response comes like below

    {"type":"value",
     "payload":{
                   "-LJXFAd_q3Cin64EBc7H":
                     {"_date":"9-8-2018",
                      "_deliveryType":"Pick up",
                      "_estDeliveryTime":"2018-08-10T11:43:57.164Z",
                       "_location":""}
}}

this on doing

the element inside payload is a key created using push. I wont know it to refer so how do i get the data under "LJXFAd_q3Cin64EBc7H" ?

there are many such entries inside payload and i need to fetch all.

code used to get above is:

getOrderHistory(uid:string){
    console.log('start of getOrderHistory with uid:' + uid)
    return new Promise((resolve, reject) =>
      {
        this.db.object("/users/" + uid + "/orders").snapshotChanges().subscribe(
          res => {
            //console.log('response:' + res)
            resolve(res)
          },
          err => {
            console.log(err)
            reject(err)
          }
        )
      })
  }

Upvotes: 1

Views: 73

Answers (2)

Joseph Webber
Joseph Webber

Reputation: 2173

Try this, it maps each snapshot to an object that holds its key and values.

this.db.object("/users/" + uid + "/orders").snapshotChanges()
.map(snapshot => {
  const key = snapshot.key;
  const data = snapshot.payload.val();
  return { key, ...data };
})
.subscribe(res => {
  resolve(res);
},
err => {
  console.log(err);
  reject(err);
});

Upvotes: 1

Ronnie Smith
Ronnie Smith

Reputation: 18595

normally, realtime database sends snapshot where you can do snapshot.id to get the id and .data (or .data() I forget at the moment) to get at the payload.

JSON.parse it then iterate it or get at it with dot notation or bracket notation. To get a property:

obj[payload][LJXFAd_q3Cin64EBc7H]

To iterate it:

function eachRecursive(obj)
{
    for (var k in obj)
    {
        if (typeof obj[k] == "object" && obj[k] !== null)
            eachRecursive(obj[k]);
        else
            // do something... 
    }
}

Upvotes: 0

Related Questions