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

Angular渲染product.category.name时抛出TypeError空引用错误

Angular嵌套对象属性访问报错修复

问题场景

基于Angular + MongoDB + NodeJS技术栈开发电商应用时,模板中访问Product对象下嵌套的category对象的name属性用于页面展示失败,控制台抛出TypeError,分类名称无法正常渲染。

相关代码与信息

产品列表模板(product-list.component.html)

<ng-template pTemplate="body" let-product>
  <tr>
    <td>{{ product.name }}</td>
    <td><img [src]="product.image" style="width: 100%; height: 100%" alt="" /></td>
    <td>{{ product.price }}</td>
    <td>{{ product.countInStock }}</td>
    <td>{{ product.category.name }}</td>
    <td>{{ product.dateCreated }}</td>
    <td>
      <p-button
        (click)="deleteProduct(product.id)"
        styleClass="p-button-danger p-mr-2"
        icon="pi pi-trash"
      ></p-button>
      <p-button
        (click)="updateProduct(product.id)"
        styleClass="p-button-success"
        icon="pi pi-pencil"
      ></p-button>
    </td>
  </tr>
</ng-template>

Postman获取的产品样例数据

{
  "richDescription": "<ul><li><strong>NVIDIA TURING™:&nbsp;</strong>ASUS GeForce RTX™ graphics cards are powered by the Turing™ GPU architecture and the all-new RTX platform. This gives you up to 6X the performance of previous-generation graphics cards and brings the power of real-time ray tracing and AI to games.</li><li><strong>DirectX 12:</strong>&nbsp;Power new visual effects and rendering techniques for more lifelike gaming.</li><li><strong>NVIDIA Shadowplay™</strong>&nbsp;Record and share high-quality gameplay videos, screenshots, and livestreams with your friends.</li><li><strong>Patented Wing-blade Fans</strong>&nbsp;deliver high air pressure, reduced noise levels, IP5X certified dust resistance, and 0dB mode for silent gaming.</li><li><strong>2.7-Slot Design</strong>&nbsp;to expand cooling surface area by more than 50% compared to last gen.</li><li>Reinforced by a&nbsp;<strong>Protective Backplate</strong>&nbsp;that prevents PCB flex and trace damage.</li><li><strong>144-Hour Validation Program</strong>&nbsp;puts cards through a series of stringent tests to ensure reliability.</li><li><strong>Auto-Extreme Technology&nbsp;</strong>uses automation to enhance reliability.</li><li><strong>Super Alloy Power II&nbsp;</strong>includes premium alloy chokes, solid polymer capacitors, and an array of high-current power stages to fuel Turing™’s cores.</li><li><strong>GPU Tweak II</strong>&nbsp;provides intuitive performance tweaking and thermal controls.</li></ul><p><br></p>",
  "image": "http://localhost:3000/public/uploads/51FcVHzQHZL._SS200_.jpg-1657440860700.jpeg",
  "images": [],
  "brand": "ASUS",
  "price": 48373,
  "rating": 0,
  "numReviews": 0,
  "isFeatured": false,
  "_id": "62ca8a5c37e02e3bbc8e8d7e",
  "name": "ASUS GeForce RTX 2060 Overclocked 6G GDDR6 ",
  "description": "Features\r\n\r\nASUS Dual GeForce RTX™ 2060 OC edition EVO 6GB GDDR6 with the all-new NVIDIA Turing™ GPU architecture.\r\n\r\nNVIDIA TURING™ GPU architecture and the all-new RTX platform provides up to 6X the performance of previous-generation graphics cards and brings the power of real-time ray tracing and AI to games.\r\nDirectX 12 enables new visual effects and rendering techniques for more lifelike gaming.\r\nNVIDIA Shadowplay™ Record and share high-quality gameplay videos, screenshots, and livestreams with your friends.\r\nAxial-tech Fan Design brings larger blades and a unique barrier ring to increase air pressure.\r\nAuto-Extreme Technology uses automation to enhance reliability.\r\nSuper Alloy Power II includes premium alloy chokes, solid polymer capacitors, and an array of high-current power stages.\r\nReinforced by a Protective Backplate that prevents PCB flex and trace damage.\r\nGPU Tweak II provides intuitive performance tweaking and thermal controls.\r\n144-Hour Validation Program puts cards through a series of stringent tests to ensure compatibility with the latest games.",
  "category": {
    "_id": "5f15d54cf3a046427a1c26e3",
    "name": "Computer",
    "__v": 0,
    "color": "#E1F0E7",
    "icon": "desktop",
    "id": "5f15d54cf3a046427a1c26e3"
  },
  "countInStock": 55,
  "dateCreated": "2022-07-10T08:14:20.710Z",
  "__v": 0,
  "id": "62ca8a5c37e02e3bbc8e8d7e"
}

前端数据模型定义

product.ts:

import { Category } from './category';
export class Product {
  id?: string;
  name?: string;
  description?: string;
  richDescription?: string;
  image?: string;
  images?: string[];
  brand?: string;
  price?: number;
  category?: Category;
  countInStock?: number;
  rating?: number;
  numReviews?: number;
  isFeatured?: boolean;
  dateCreated?: string;
}

category.ts:

export class Category {
  id?: string;
  name?: string;
  icon?: string;
  color?: string;
}

控制台报错信息

core.js:6210 ERROR TypeError: Cannot read properties of null (reading 'name')
    at ProductsListComponent_ng_template_12_Template (products-list.component.html:48:19)
    at executeTemplate (core.js:9614:1)
    at refreshView (core.js:9480:1)
    at refreshEmbeddedViews (core.js:10605:1)
    at refreshView (core.js:9504:1)
    at refreshEmbeddedViews (core.js:10605:1)
    at refreshView (core.js:9504:1)
    at refreshEmbeddedViews (core.js:10605:1)
    at refreshView (core.js:9504:1)
    at refreshComponent (core.js:10651:1)

报错原因

报错的核心触发逻辑有两点:

  • 模板首次渲染时,产品列表的异步接口请求还未返回,此时product对象的category字段值为null,直接访问.name属性就会触发空值读取错误
  • 部分产品数据可能未关联分类,后端返回的对应category字段本身就是null,渲染时同样会触发报错
    Postman中能拿到完整嵌套数据,仅代表接口请求成功后的数据结构符合预期,无法覆盖渲染时序问题和异常数据场景。

修复方案

按落地成本从低到高排序:

  • 模板层加安全导航符(推荐优先使用)
    用Angular内置的安全导航操作符?,自动判断前序属性是否为null/undefined,为空时终止属性访问,不会抛出错误,数据加载完成后自动渲染正确值。
    仅需修改模板中对应行代码:
    <td>{{ product.category?.name }}</td>
    
  • 用*ngIf控制渲染时机
    等category字段存在时再渲染对应DOM,可搭配加载占位符优化体验:
    <td *ngIf="product.category; else loadingTpl">{{ product.category.name }}</td>
    <ng-template #loadingTpl><td>-</td></ng-template>
    
  • 数据源层补全校验
    排查NodeJS接口的产品查询逻辑,确认MongoDB关联分类的$lookup查询是否正常,补全缺失分类的产品数据,从源头避免空值返回。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 02:03:24