Search code examples
ionic-frameworkangularfire2

converting angularfirelist to array


I would like to ask how to subscribe an angularfirelist to an array of objects. This way doesn't work, here is a preview of my code

 Moniteurs: MoniteurModel[]; 

 constructor(public navCtrl: NavController, 
    public navParams: NavParams,
    public db:AngularFireDatabase, 
    public http: HttpClient) {
        this.db.list<MoniteurModel[]>('/Pannes').valueChanges().subscribe((data)=>{
        this.Moniteurs.push(data);
   }

Solution

  • I want to say there are a few things that can be addressed, but my primarily you are pushing an array from your valuesChanges() subscription into an array. I doubt you wanted that and would rather update the Moniteurs array with the new values from Firebase:

      Moniteurs: MoniteurModel[]; 
    
      constructor(public navCtrl: NavController, 
         public navParams: NavParams,
         public db:AngularFireDatabase, 
         public http: HttpClient) {
    
        this.db.list<MoniteurModel>('/Pannes').valueChanges().subscribe((values) => {
          // If you want to push in values, however this may lead to duplicates
          values.forEach((value) => this.Moniteurs.push(value));
    
          // If you want Moniteurs to be just the new data
          this.Moniteurs = values;
        });
      }