使用 AngularFire2 作为列表检索数据

Retrieve data using AngularFire2 as a list

   import { Injectable } from '@angular/core';
    import { AngularFireDatabase } from '@angular/fire/database';
    import { Observable } from 'rxjs';

    @Injectable({
      providedIn: 'root'
    })
    export class FirebaseService {
      listings: Observable<any[]>;
      constructor(private db: AngularFireDatabase) { }

      getListings(){
        this.listings = this.db.list('/listings') as Observable<Listing[]>
        return this.listings;
      }
    }

    interface Listing{
      $key?:string;
      title?:string;
      type?:string;
      image?:string;
      city?:string;
      owner?:string;
      bedrooms?:string;
    }

我正在尝试使用 angularfirer2 从 Firebase 中以列表形式检索数据。但是在 this.listings = this.db.list('/listings') as Observable<Listing[]> 中我收到一条错误消息

Conversion of type 'AngularFireList<{}>' to type 'Observable' may be a mistake because neither type sufficiently overlaps with the other.

谁能帮我解决这个问题。

您可以像这样在 .service 文件中创建一个单独的 getListing 函数。

    getEmployees() {
        return this.firestore.collection('employees').snapshotChanges();
    }

然后调用组件.ts文件中的getEmployees函数

    list: Employee[];
     ngOnInit() {
    this.service.getEmployees().subscribe(actionArray => {
      this.list = actionArray.map(item => {
        return {
          id: item.payload.doc.id,
          ...item.payload.doc.data()
        } as Employee;
      })
    });
    }

然后就可以像下面这样通过List的for循环获取HTML文件中的数据了

     <tbody>
    <tr *ngFor="let emp of list">
      <td >{{emp.empCode}} - {{emp.fullName}}</td>
      <td >{{emp.position}}</td>
      <td >{{emp.mobile}}</td>
    </tr>
  </tbody>