Search code examples
angulartypescriptfirebasefirebase-realtime-databaseangularfire2

How to retrieve specific values from a list in AngularFire2


I have a Firebase Realtime Database that looks like this:

Items:
    Object0:
        value1: "Foo-0"
        value2: "Bar-0"
    Object1:
        value1: "Foo-1"
        value2: "Bar-1"
    ...

... and so on, cut it down to simplify. Every "ObjectX" contains exactly the same structure, like value1, value2... The only difference between them is the values of value1, value2.

I need to get value1 from each of the objects. I can do that now by getting each object and assigning the values to a variable:

import { AngularFireDatabase } from '@angular/fire/database';
...
export class FooComponent{
  objectOne: ObjectModel = <ObjectModel>{};
  objectTwo: ObjectModel = <ObjectModel>{};

  constructor(private firebase: AngularFireDatabase) {}
  ngOnInit() {
    this.firebase
      .object('/Items/Object0')
      .valueChanges()
      .subscribe((objectm: ObjectModel ) => {
        this.objectOne = objectm; }

    this.firebase
      .object('/Items/Object1')
      .valueChanges()
      .subscribe((objectm: ObjectModel ) => {
        this.objectTwo = objectm; }

  valueOne = this.objectOne.value1; //"Foo-0"
  valueTwo = this.objectTwo.value1; //"Foo-1"
  }
}
export interface ObejctModel {
    value1: string;
    value2: string;   
  }

I imagine there is a way easier way to do this using firebase.list('/Items') instead of firebase.object, but I can't seem to find any solution that works for me. Can anyone help me refactor this code so it only uses 1 list instead of 2 (or more) objects?

Also, I must assign the values to variables in typescript, not the usual {{ items | async }} in the template approach.


Solution

  • You can do the following:

    this.firebase.list('/Items').valueChanges().subscribe(items => {
         console.log(items);  
         items.forEach(values=>{ console.log(values) });
        });
    

    The items will contain all the objects and the values in your database. You can also use forEach to iterate inside the array, that way you can access value1 and value2 without knowing the keys (Object0 and Object1).