Anjali
Anjali

Reputation: 1

unable to display data using Firebase and Angular

app.comoponent.ts

export class AppComponent {
    Angular: any[] = [];


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

  })
}

-----------

app.component.html

<ul>
  <li *ngFor= "let course of Angular">
    {{course.$values}}
  </li>
</ul>

Not able to see data on in Templet. Console is showing values in array which are from firebase. ["course1", "course2", "course3"] when expanded it is showing key value pairs but not $value to grab it. Not sure how it works. I am fairly new to this field.

Upvotes: 0

Views: 22

Answers (2)

Raz Ronen
Raz Ronen

Reputation: 2638

Try:

app.comoponent.ts

export class AppComponent {
    Angular: Observable<any[]>;


constructor(db: AngularFireDatabase){
  this.Angular = db.list('/Angular').valueChanges();
  
}

app.component.html

<ul *ngIf="Angular">
  <li *ngFor= "let course of Angular | async">
    {{course}}
  </li>
</ul>

If you use async pipe then change detection will allways kick in when observable emits a value, in your case Angular.

Upvotes: 1

Mr.Manhattan
Mr.Manhattan

Reputation: 5504

So first of all, let's get the types straight.

export class AppComponent {
    // as your console.log showed, this is a simple string array:
    courseList: string[] = [];
}

Note that i changed the name of the variable, Angular doesn't properly describe it's content. But that is ofc personal taste. Also note that instance variables are usually declared in camelCaps, starting with a small letter. But that again, is personal taste.

Then, angular provides lifecycle hooks. fetching async data should be done in the ngOnInit function:

export class AppComponent implements OnInit {
    courseList: string[] = [];

    constructor(private db: AngularFireDatabase){};

    ngOnInit() {
        this.db.list('/Angular').valueChanges().subscribe(courseList => {
            this.courseList = courseList;
            console.log(this.courseList);
        });
    }
}

now in the template, you can bind directly to the values:

<ul>
  <li *ngFor= "const course of courseList">
    {{course}}
  </li>
</ul>

Upvotes: 0

Related Questions