首页 > 解决方案 > Ionic5/Angular - 尝试区分“[object Object]”时出错。只允许使用数组和可迭代对象

问题描述

当我想在 HTML 中显示 firebase 子集合时出现此错误。它确实显示在控制台中,但不在 UI 中。

我收到这个错误。控制台图像

TS文件

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;
  storedData: any = [];
  constructor(
    private auth: AuthService,
    private router: Router,
    private afs: AngularFirestore
  ) {}

  ngOnInit() {
    this.auth.user$.subscribe((user) => {
      this.userId = user.userId;
    });
  }

  fetchBookings() {
    this.afs
      .collection('user')
      .doc(this.userId)
      .collection('BookingHistory')
      .get()
      .subscribe((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          console.log(doc.id, ' => ', doc.data());
          this.storedData = querySnapshot;
        });
      });
  }
}

HTML 文件

<ion-item *ngFor="let data of storedData">
    <ion-label>{{data.TimeSlot}}</ion-label>
    <ion-label>{{data.BookedAt}}</ion-label>
    <ion-label>{{data.BookingDate}}</ion-label>
</ion-item>

标签: htmlangularfirebaseionic-framework

解决方案


我会尝试这样的事情,

只要querySnapshot返回没有任何嵌套对象的storedData数组,您就可以直接设置它,否则您必须通过响应结构中的正确条目读取它,并在HTML模板中相应地从列表中读取值

fetchBookings() {
    this.afs
      .collection('user')
      .doc(this.userId)
      .collection('BookingHistory')
      .get()
      .subscribe((querySnapshot) => {
        querySnapshot.forEach((doc) => { // or you can remove this forEach() and set the querySnapshot (if it returns an array of storedData) directly 
          console.log(doc.id, ' => ', doc.data());
          this.storedData.push(doc);
        });
      });
  }
}

推荐阅读