
本文详解 Angular 应用中因数据结构嵌套(如 Rows.$values)导致 *ngFor 无法渲染表格的问题,并同步解决 Vite 开发服务器下的 source map 404 报错,适用于 Angular 17+ 项目。
本文详解 angular 应用中因数据结构嵌套(如 `rows.$values`)导致 `*ngfor` 无法渲染表格的问题,并同步解决 vite 开发服务器下的 source map 404 报错,适用于 angular 17+ 项目。
在 Angular 17 项目中,表格数据「看似已获取却始终空白」,往往并非请求失败或模板语法错误,而是数据结构与模板预期严重错配所致。从你提供的调试日志可见:后端返回的 data.Rows 并非原生数组,而是一个包含 $id 和 $values 属性的对象(典型如 ASP.NET Core Web API 启用 ReferenceHandler.Preserve 时的序列化行为)。此时直接使用 Array.isArray(data.Rows) 判断会返回 false,导致 this.rows 被错误赋值为 [data.Rows](即单元素数组,其唯一元素仍是对象),最终 *ngFor 迭代失败——因为 row.Number 等属性在该对象上并不存在。
✅ 正确解构嵌套数组结构
需明确访问 data.Rows.$values 才能获取真实的数据数组。修改 ngOnInit() 中的数据处理逻辑如下:
ngOnInit() {
this.addRow();
this.id = this.route.snapshot.paramMap.get('id')!;
this.qrtService.get(this.id)
.subscribe({
next: (data: QRT) => {
console.log('Received object in ngOnInit:', data);
this.report = data;
// 关键修正:检查并提取 $values 数组
if (data.Rows && Array.isArray(data.Rows.$values)) {
this.rows = data.Rows.$values; // 直接赋值数组
} else {
console.warn('Expected Rows.$values to be an array, got:', data.Rows);
this.rows = []; // 安全兜底:空数组避免模板报错
}
},
error: (error) => {
console.error('Error fetching report data', error);
this.rows = []; // 请求失败时也确保 rows 为数组
}
});
}
? 注意:this.rows 必须始终为 any[] 类型(或更严格的 RowModel[]),不可为 null、undefined 或普通对象。Angular 的 *ngFor 对非数组值静默失败,无控制台报错,极易被忽略。
?️ 模板健壮性增强(推荐)
为防止 row 属性访问时报 Cannot read property 'xxx' of undefined,建议在模板中添加安全导航操作符(?.)或使用 *ngIf 预检:
<tbody> 0; else noData">
<tr row of rows let i='index"'>
<td>{{ row?.Number }}</td>
<td>{{ row?.TestedProcessName }}</td>
<td>{{ row?.TestingDescription }}</td>
<td>{{ row?.SampleData }}</td>
<td>{{ row?.TestingActivities }}</td>
<td>{{ row?.DetectedIrregularities }}</td>
<td>{{ row?.IrregularityCategory }}</td>
<td>{{ row?.CorrectiveActions }}</td>
<td>{{ row?.CorrectiveActionDeadline }}</td>
</tr>
</tbody><ng-template><tr>
<td colspan="9" class="text-center text-muted">暂无数据</td>
</tr></ng-template>
? Source Map 404 错误:Vite 特定问题
你遇到的 Source Map Error: request failed with status 404(资源 URL 为 https://localhost:44498/@vite/client)是 Vite 开发服务器配置与 Angular 集成不完善所致,与数据渲染无关,但影响调试体验:
- 原因:Angular 17 默认支持 Vite 构建,但部分项目可能未正确初始化 Vite 配置,或 @vite/client 的 source map 文件未被正确托管。
-
快速修复:
- 确保已安装最新版 @angular-devkit/build-angular(≥17.3.0);
- 在项目根目录运行:
ng update @angular-devkit/build-angular
- 清理并重启开发服务器:
rm -rf node_modules/.vite ng serve
- 临时规避:在浏览器开发者工具 → Settings → Preferences → Sources 中,取消勾选 Enable JavaScript source maps 和 Enable CSS source maps(仅限调试阶段)。
✅ 总结
| 问题类型 | 根本原因 | 解决方案 |
|---|---|---|
| 表格无数据 | data.Rows 是含 $values 的对象,未正确解构 | 改为 data.Rows.$values 并确保 this.rows 为数组 |
| Source Map 404 | Vite 客户端映射文件缺失或路径错误 | 更新构建工具、清理缓存、重启服务 |
只要确保 this.rows 是一个可迭代的数组,且模板中属性名与 $values 内对象结构完全一致,表格即可立即渲染。务必在 subscribe 的 error 和 else 分支中为 this.rows 提供明确的数组默认值(如 []),这是 Angular 响应式模板稳定性的关键实践。











