You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ionic的HTML页面中展示Firebase子集合数据

代码调整方案

1. 修改TypeScript业务代码

你当前仅将查询到的数据输出到控制台,没有存储到组件的公共属性中,因此模板无法访问到对应数据。需要新增存储预订数据的数组属性,同时修改查询逻辑将数据存入数组:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';
import { AngularFirestore } from '@angular/fire/compat/firestore';

@Component({
  selector: 'app-my-reservations',
  templateUrl: './my-reservations.page.html',
  styleUrls: ['./my-reservations.page.scss'],
})
export class MyReservationsPage implements OnInit {
  user: any;
  userId: string;
  // 新增:存储预订数据的公共数组
  bookings: any[] = [];

  constructor(
    private auth: AuthService,
    private router: Router,
    private afs: AngularFirestore
  ) {}

  ngOnInit() {
    this.auth.user$.subscribe((user) => {
      this.userId = user.userId;
      // 可选:拿到用户ID后自动加载数据,无需手动点击按钮
      // this.fetchBookings();
    });
  }

  fetchBookings() {
    // 每次查询前清空旧数据,避免重复渲染
    this.bookings = [];
    this.afs
      .collection('user')
      .doc(this.userId)
      .collection('BookingHistory')
      .get()
      .subscribe((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          console.log(doc.id, ' => ', doc.data());
          // 将文档ID和字段数据一起存入数组
          this.bookings.push({
            id: doc.id,
            ...doc.data()
          });
        });
      });
  }
}

2. 修改HTML模板代码

直接遍历存储数据的bookings数组即可,插值表达式中填写你Firebase的BookingHistory集合中实际存储的字段名即可:

<ion-content>
    <ion-button (click)="fetchBookings()">加载我的预订</ion-button>
   
    <ion-item *ngFor="let booking of bookings">
      <!-- 示例字段,需替换为你Firebase文档中实际的字段名,大小写需完全一致 -->
      <ion-label>
        预订ID:{{booking.id}}<br>
        服务名称:{{booking.serviceName}}<br>
        预订时间:{{booking.bookingTime}}<br>
        订单金额:{{booking.amount}}
      </ion-label>
    </ion-item>
</ion-content>

可选优化

  • 如需实时同步Firebase的数据更新,无需每次手动点击拉取,可将get()方法替换为valueChanges()或snapshotChanges()订阅,数据变更会自动同步到页面
  • 建议为预订数据定义TS接口替换any类型,可获得更好的类型提示与错误校验

内容的提问来源于stack exchange,提问作者Victor Nem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 08:06:03