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

Angular12报TypeError: cannot read property of undefined 分类列表无数据

错误原因
  • 接口返回值处理逻辑与实际类型不匹配:CategoriesService中getCategories方法声明返回Category[]类型的分类数组,但组件订阅接口时错误尝试读取返回值的categories属性,若后端直接返回数组,data本身就是分类列表,不存在categories属性,会导致this.categories被赋值为undefined,模板读取undefined的属性时就会抛出对应类型错误。
  • 模板语法不符合PrimeNG表格规范:pTemplate="body"的ng-template由PrimeNG表格内部控制遍历逻辑,不需要手动添加*ngFor,重复声明let-category也属于无效语法,会进一步导致渲染异常。
修复方案
  1. 修正组件内的接口订阅逻辑,直接使用返回的数组赋值:
    修改categories-list.component.ts中的getCategories方法:
private getCategories() {
  this.categoriesService.getCategories().subscribe( (data: Category[]) => {
    this.categories = data
    console.log(data)
  })
}
  1. 修正模板渲染语法,移除多余的*ngFor和重复的变量声明:
    修改categories-list.html代码:
<ng-template pTemplate="body" let-category>
        <tr>
            <td>{{category.id}}</td>
            <td>{{category.name}}</td>
            <td>{{category.icon}}</td>
        </tr>
 </ng-template>

补充说明:如果控制台打印的data确实是包含categories字段的对象,说明Service的返回类型声明错误,需要同步修改categories.service.ts中的getCategories方法返回类型:

getCategories(): Observable<{categories: Category[]}> {
  return this.http.get<{categories: Category[]}>(`${this.apiMainUrl}/categories`)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:15:01