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报错。
修复步骤
- 修改模板中保存按钮的click事件绑定,传入
$event对象:
<a href="#save-seminar" (click)="saveSeminar(i, $event)"> <i class="fa fa-check"></i> </a>
- 修改ts中
saveSeminar方法的参数定义,接收传入的事件对象:
private saveSeminar(index: number, event: Event) { event.preventDefault(); console.log(index) this.updateUserSeminar(index); }
- 修正
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
相关产品推荐
相关产品推荐

