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

Angular提交数据报错:无法读取undefined的bookingHistoryListDO属性

报错核心原因
  • 你在BookingHistoryList类中仅声明了bookingHistoryListDO的类型,未对其做初始化赋值,该属性默认值为undefined,对undefined调用.push()方法就会触发读取undefined属性的报错。
  • 你通过JSON.parse(localStorage.getItem('currentUser'))拿到的是普通JavaScript对象,不是CreateUser类的实例,序列化/反序列化过程会丢失类的原型和构造函数逻辑,嵌套的bookingHistoryList属性不会自动执行你写的初始化逻辑。

你之前尝试修改为内联数组类型的写法依然报错,原因完全一致:只声明类型不赋值,属性永远是undefined。

修复方案

1. 初始化BookingHistoryList类的数组属性

修改BookingHistoryList.ts代码,在构造函数中为数组赋初始空值:

import { Booking } from "./Booking";

export class BookingHistoryList {
    bookingHistoryListDO : Booking[];
    constructor() {
        // 初始化为空数组,解决undefined问题
        this.bookingHistoryListDO = [];
    }
}

2. 修复localStorage反序列化丢失实例的问题

在home.component.ts的getBookingFormData方法中,取出缓存的用户数据后增加非空兜底,同时按Booking类结构构造要提交的预订数据:

// 首先记得在文件顶部引入BookingHistoryList和Booking类
import { BookingHistoryList } from 'src/app/BookingHistoryList';
import { Booking } from 'src/app/Booking';

// ...省略其他代码
else
{
  // 兜底处理:如果缓存对象丢失嵌套属性,手动重新初始化
  if (!this.currentUser.bookingHistoryList) {
    this.currentUser.bookingHistoryList = new BookingHistoryList();
  }
  // 构造符合Booking类结构的对象
  const newBooking = new Booking();
  newBooking.fromCity = this.booking.fromCity;
  newBooking.toCity = this.booking.toCity;
  newBooking.date = this.booking.date;
  // 此时数组已经初始化完成,可以正常push
  this.currentUser.bookingHistoryList.bookingHistoryListDO.push(newBooking);
  console.log(this.currentUser);
  // 更新本地缓存,避免下次读取还是旧数据
  localStorage.setItem('currentUser', JSON.stringify(this.currentUser));
  this.postRequest.sendUserData(this.currentUser);
}

3. 冗余代码修正

你在home.component.ts中定义的booking对象不需要加非空断言!,直接初始化即可:

booking = {
  fromCity: "",
  toCity: "",
  date: ""
}
注意事项
  • 类中声明的引用类型属性(数组、自定义类实例),如果声明时没有直接赋值,必须在构造函数中初始化,否则默认值为undefined,调用时必然报错。
  • localStorage仅支持存储字符串,经过JSON.stringify和JSON.parse转换后,所有类的原型方法、构造函数逻辑都会丢失,得到的只是普通键值对对象,涉及嵌套类结构的数据,读取后必须手动做实例恢复或非空校验。

内容的提问来源于stack exchange,提问作者Jay Mistry

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 01:27:29