Search code examples
typescriptfirebaseionic-frameworkfirebase-realtime-databaseangularfire

Error at Converting A Firebase Database Snapshot To An Array In TypeScript


I've been following this tutorial https://ilikekillnerds.com/2017/05/convert-firebase-database-snapshotcollection-array-javascript/ in order to convert a firebase snapshot into an array in my ionic application. This is the code I have:

https://github.com/dladinot/AplicativoTutoriasMoviles/blob/master/src/pages/buscar-tutor/buscar-tutor.ts

And this is my data structure in firebase:

enter image description here

When I use my code this is the error it gives me:

enter image description here

And when I debbug that line of code where the error seems to be, I can see that the first item in the snapshot is stored in the array, then the next value is undefined. Although if I just print the keys it prints just fine:

enter image description here

Anyone has any idea what's going on?


Solution

  • you have several boolean properties in your database like boolLogin and disponible. hence when you are using foreach to iterate the values and add a key to them you are getting this error because it's trying to add key to the item even when it has boolean value in this line

    item.key=childSnapshot.key;

    try to add the snapshots to the array using the below code

    this.consultaTutor=this.afDatabase.object(`profile/SlHGkc3ZK0hHxH2s1sowpgGuJfA3`, {preserveSnapshot: true})
              this.consultaTutor.subscribe(info=>{
                info.forEach(childSnapshot=>{  
                  var value = childSnapshot.val();
                  var key = childSnapshot.key;
                  console.log(childSnapshot.key);
                  var item = { "key" : key, "value" : value};
                  this.listaTutores.push(item);      
                })