html - 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>
解决方案
我会尝试这样的事情,
只要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);
});
});
}
}
推荐阅读
- python - 如何将字符串拆分为变量?
- javascript - ECharts:改变线条颜色
- amazon-web-services - 使用多个登录名的 Cognito Identity
- javascript - 如何比较数组和更新数量?
- java - 我怎样才能只在父类中@Required
- java - 使用 ASM 重命名类会在编译的 jar 上引发 ClassCastException 和 AbstractMethodError
- java - Java Jackson 序列化忽略带有注释的特定嵌套属性
- java - Java WeakHashMap 什么时候会清理空键?
- php - 使用 PHP 在 Datepicker 上的选定日期上添加天数
- c++ - 跳棋多跳计数算法