angular - 如何在 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>
解决方案
您的实施目前存在几个问题。
第一个问题是您需要将结果分配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 };
});
})
);
});
希望这会有所帮助!
推荐阅读
- java - 在结果集中找不到列
- html - 将 HTML 内容从 SQL 数据库移动到 XML 文件以进行 Wordpress 导入
- openstreetmap - 如何计算一个节点出现的总次数是一种方式的集合?
- c# - C#:我的应用程序是否可以共享在我的其他类之一中触发的事件?
- typescript - 提取自己的类属性/成员类型
- sql - Oracle - 缺少左括号
- android - 如何通过BluetoothGatt在两部Android手机中相互通信
- upc - 如何解决 UPC 运行时错误:共享内存不足
- google-cloud-platform - Neo4j 本地与云的性能差异
- javascript - 单击按钮以删除自身及其父 div