2

When I get all items from a JSON table in Firebase, it returns them as object of objects.

How do I get Firebase to return me an array of objects so that it works nicely with my ngFor?

I'm using angular 2 beta and typescript with Firebase.

This is the current structure returned from Firebase:

 {{"item": ""}, {"item": ""}, {"item": ""}}

I want this (array of objects):

 [{"item": ""}, {"item": ""}, {"item": ""}}]

This is my firebase code that works:

 var query = this.refJob.orderByChild('status').equalTo('Active'); 

query.on('value', (snap) => {               
    resolve(snap.val());    
});

Is there something I can do after equalTo to organise the results into an array?

Current bug:

enter image description here

1 Answer 1

1

You can order them into an array on the client-side.

var query = this.refJob.orderByChild('status').equalTo('Active'); 
var array = [];
query.on('value', (snap) => {
  snap.forEach((child) => {
     var item = {};
     item._key = snap.key();
     array.push(item));
  });
});

Also, don't use promises with .on(), because .on() can/will be called several times, whereas promises only get called once.

If you want to use something like promises for Firebase and Angular 2, look into using Observables.

Sign up to request clarification or add additional context in comments.

3 Comments

I've tried your code and it returns this "[Q]" with loads of weird lists in the array and not an array of my objects
I've added above the screen shot of the console for your code
That's a FirebaseDataSnapshot, it looks weird because the property names are minified for performance. If you call .val() the snapshot will return the object. The snapshot is good to keep around because it holds the key and other helpful functions. I've updated my code to show a trick you can do to get the item with the key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.