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

Angular前端展示嵌套对象中经纬度数据的问题

Angular展示嵌套对象中经纬度的解决方案

你的问题出在错误使用了*ngFor指令——*ngFor是用来遍历数组或可迭代对象的,但从你描述的嵌套Object结构来看,geometry、location应该是单个对象,lat和long是普通数值,根本不需要循环遍历。

正确写法示例

如果trail.geometry是单个对象:

<!-- 先判断属性存在避免空指针错误 -->
<div *ngIf="trail?.geometry?.location">
  纬度:{{ trail.geometry.location.lat }}<br>
  经度:{{ trail.geometry.location.long }}
</div>

如果trail.geometry是数组(存在多个geometry的情况):

<ng-container *ngFor="let geometry of trail?.geometry">
  <div *ngIf="geometry?.location">
    纬度:{{ geometry.location.lat }}<br>
    经度:{{ geometry.location.long }}
  </div>
</ng-container>

为什么之前的代码无效

你之前的代码对geometry、location、lat都用了*ngFor,但这些都不是数组:

  • 对单个对象用*ngFor不会生成任何DOM元素
  • 对单个数值lat用*ngFor同样不会有遍历结果,自然无法展示值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:45:31