首页 > 解决方案 > 如何在 firestore 和 ionic 4 中使用 snapshotChanges()

问题描述

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

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

我的代码在下面:

新闻页面.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 };
      });
    });
}

新闻.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>

标签: angularionic3google-cloud-firestoreionic4

解决方案


您的实施目前存在几个问题。

第一个问题是您需要将结果分配this.db.collection('123').snapshotChanges()...给您的news: Observable<any[]>类属性,以便能够有效地使用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 操作符。这将涉及更新您对map运算符的导入以及更新它与snapshotChanges(). 实际上它只是在map()里面移动pipe()

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 };
      });
    })
  );
});

希望这会有所帮助!


推荐阅读