Problem Displaying Data with Firebase and Ionic

I’m working with the Ionic Framework and Firebase to create an app but I’m running into some trouble. I can’t display my data from Firebase. I’m creating a database for the courses at my school and I want to display the name one course at a time.

I want course1.name to return math but I’m getting an undefined error when I do that. The only way I can get it to display data is if I do course.name which returns both math and art. But I only want to display the name of one course at a time.

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AngularFireDatabase } from 'angularfire2/database';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  courses: any[];

  constructor(db: AngularFireDatabase) {
    db.list('/courses').valueChanges()
      .subscribe(result => {
        this.courses = result;
        console.log(this.courses);
    });

  }

}

home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Banner Mobile
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ul>
    <li *ngFor="let course of courses">
      {{ course1.name }}
    </li>
  </ul>
</ion-content>

Firebase Database Picture

Your list does not know what course1 is. It only knows that it is a list of some things. In this case, courses because you made it so when you said “let course of courses”.

Change

{{ course1.name }}

To

{{ course.name }}

Fyi if you say “let c of courses”

{{ c.name }}

Will display each individual c’s name.

If you want to only display course1’s name, dont try to do so in a list. You would have to use {{ courses[0].name }} without *ngFor to get the first course’s name

when I do {{ courses[0].name }} without *ngFor, I get an error “Cannot read property ‘0’ of undefined.” Do I have to change anything in the home.ts file?

Yes, every time you declare an array property that will be referenced from a template, initialize it to something sane like []. Same goes for objects and {}. Do not leave them uninitialized. Also, it will really help your productivity if you discipline yourself to never type any in your code.

1 Like

Now I’m getting the error "Cannot read property ‘name’ of undefined.”

Hello,

Looks like you have an async issue, I mean the data is checked before it is written. And if the data is checked before it is written, Ionic crash (if no errors methods in place - with AngularFire).

Have fun with Ionic,

Put ‘?’ as follows and you will get resolve the console
{{ course?.name }}