Ionic Angular中如何在页面展示Firestore单个文档数据?
解决Ionic/Angular中Firestore数据无法在HTML展示的问题
环境:Angular CLI: 13.0.4,Ionic: 6.20.2
问题
已在Firestore创建集合并填充数据,控制台能打印集合首个文档数据,但无法在HTML页面展示该数据。
最简解决方案
1. 修改组件TypeScript代码
在组件类中定义变量存储数据,并在订阅Firestore数据流时将数据赋值给该变量:
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import {AngularFirestore} from "@angular/fire/compat/firestore"; @Component({ selector: 'app-first-place', templateUrl: './first-place.page.html', styleUrls: ['./first-place.page.scss'], }) export class FirstPlacePage implements OnInit { // 声明变量存储要展示的文档数据 currentRentPlace: any; constructor( private router: Router, private afs: AngularFirestore, ) {} ngOnInit() { this.afs.collection('rentplace').valueChanges() .subscribe(value => { // 将集合首个文档数据赋值给类变量 this.currentRentPlace = value[0]; }); } }
2. 修改HTML模板代码
通过Angular数据绑定展示数据,同时用*ngIf避免数据未加载时的报错:
<!-- 确保数据存在后再渲染内容 --> <div *ngIf="currentRentPlace"> <h3>{{ currentRentPlace.rentplaceTitle }}</h3> <p>水上自行车数量:{{ currentRentPlace.rentplaceWaterBike }}</p> <p>SUP数量:{{ currentRentPlace.rentplaceSup }}</p> <p>所有者邮箱:{{ currentRentPlace.rentplaceOwnerEmail }}</p> </div>
关键说明
- 必须将异步获取的Firestore数据赋值给组件类的成员变量,HTML才能通过数据绑定访问到这些数据
*ngIf="currentRentPlace"会在数据加载完成前隐藏元素,避免出现undefined相关的渲染错误- 用插值表达式
{{ }}直接读取变量的属性值完成展示
内容的提问来源于stack exchange,提问作者dttamas
相关产品推荐
相关产品推荐

