如何呈现从Firebase检索的列表

时间:2018-12-26 15:32:29

标签: javascript html angular firebase

我想用从Firebase检索的数据在有角项目中渲染一个列表,但无法将其渲染到我的列表中。

我尝试了Angular 7

//this is my ts code
import { Component } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { PassThrough } from 'stream';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  courses: any[];
  constructor(db: AngularFireDatabase) {
    db.list('/courses').snapshotChanges().subscribe(courses =>{
        this.courses = courses;
        console.log(this.courses);
      });
    }
  }



//this is the html 
<ul>
  <li *ngFor="let course of courses">
    {{course.value}}
  </li>
</ul>

我希望它像这样显示

  • course1
  • course2

但列表仅显示一个这样的点

-

2 个答案:

答案 0 :(得分:0)

内部subscribe()this不引用courses,您需要将this分配给另一个变量,例如let self=this;

尝试以下代码,希望对您有用

import { Component } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { PassThrough } from 'stream';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
  courses: any[];
  constructor(db: AngularFireDatabase) {
  let self=this;
  db.list('/courses').snapshotChanges().subscribe(courses =>{
        self.courses = courses;
        console.log(courses);
     });
  }
}

答案 1 :(得分:0)

小问题,您无法将节点分配给this.courses

export class AppComponent {
  courses: any[];
  constructor(db: AngularFireDatabase) {

   db.list('/courses').snapshotChanges().pipe(
      map(changes => 
        changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
      )
    ).subscribe(courses =>{
        this.courses = courses;
        console.log(this.courses);
      });

    }
  }

ref:https://github.com/angular/angularfire2/blob/master/docs/rtdb/lists.md

还要确保Course对象中的course.value,“ value”属性存在。

<ul>
  <li *ngFor="let course of courses">
    {{course.value}} <-- here ?? 
  </li>
</ul>