AngularM
AngularM

Reputation: 16628

How do I get an array of objects from Firebase?

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

Upvotes: 2

Views: 1115

Answers (1)

David East
David East

Reputation: 32604

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.

Upvotes: 1

Related Questions