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

Angular 11保存数据报Cannot read properties of undefined (reading '0')

报错根因

代码中有两处直接触发undefined错误的问题:

  • click事件未传递$event对象:saveSeminar方法内直接调用event.preventDefault(),但模板绑定事件时没有把事件对象传入,运行时event为undefined,调用方法直接抛错。
  • 数组变量名拼写不统一:模板中*ngFor遍历的数组是userSeminar,但ts逻辑里写的是this.userSeminars(末尾多了个s),访问不存在的属性会返回undefined,再通过下标取元素属性时必然触发undefined报错。
修复步骤
  1. 修改模板中保存按钮的click事件绑定,传入$event对象:
<a href="#save-seminar" (click)="saveSeminar(i, $event)">
  <i class="fa fa-check"></i>
</a>
  1. 修改ts中saveSeminar方法的参数定义,接收传入的事件对象:
private saveSeminar(index: number, event: Event) {
    event.preventDefault();
    console.log(index)
    this.updateUserSeminar(index);
}
  1. 修正updateUserSeminar方法中的数组名,和模板定义保持一致,去掉末尾多余的s:
private updateUserSeminar(index: number) {
    this.apiService.update('users/seminar', this.userSeminar[index].id, this.userSeminar[index])
    .subscribe(
    response => {
        console.log('Seminar Successfully updated', 'Success');
    });
}

补充:如果不需要a标签的锚点跳转行为,也可以直接把href属性改成href="javascript:void(0)",省去调用preventDefault的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 18:18:51