如何将 snapshotChanges() 与 firestore 和 ionic 4 一起使用

How to use snapshotChanges() with firestore and ionic 4

嗨,我的朋友们,我的 ionic4 应用程序中有代码可以从 firestore 检索数据,我尝试使用此代码来执行此操作,但它没有显示任何这些数据

我尝试在我的代码中使用 snapshotChanges() 但失败了 我也想检索文档的 ID 我该怎么做

我的代码在下面:

news.page.ts

import { Component, OnInit } from '@angular/core';
import {AngularFirestore, AngularFirestoreDocument} from 'angularfire2/firestore';
import {Observable} from 'rxjs';
import { Router } from '@angular/router';
import 'rxjs/add/operator/map';
export class FilmsPage implements OnInit {
  news: Observable<any[]>;
  constructor(public db: AngularFirestore, private router: Router) { }

  ngOnInit() {
      this.db.collection('123').snapshotChanges().map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data();
        const id = a.payload.doc.id;
        return { id, ...data };
      });
    });
}

news.page.html

<ion-content padding>
        <ion-item *ngFor=" let count of news | async">
          <ion-button routerLink="/details/{{count.id}}">{{count.name}} -> id: {{count.id}}</ion-button>

</ion-item>
</ion-content>

目前您的实施存在一些问题。

第一个问题是您需要将 this.db.collection('123').snapshotChanges()... 的结果分配给您的 news: Observable<any[]> class 属性 才能有效地使用 async 管道在你的模板中:

ngOnInit() {
  this.news = this.db.collection('123').snapshotChanges().map(actions => {
    return actions.map(a => {
      const data = a.payload.doc.data();
      const id = a.payload.doc.id;
      return { id, ...data };
    });
});

下一期取决于您的 RxJS 版本。如果你的项目使用 RxJS 5.5+,你应该使用 pipeable operators。这将涉及更新 map 运算符的导入以及更新它与 snapshotChanges() 一起使用的方式。实际上它只是在 pipe():

内移动 map()
import { map } from 'rxjs/operators';

// ...

ngOnInit() {
  this.news = this.db.collection('123').snapshotChanges().pipe(
    map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data();
        const id = a.payload.doc.id;
        return { id, ...data };
      });
    })
  );
});

希望对您有所帮助!