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

Angular中用ngFor结合Async Pipe遍历嵌套JSON展示经纬度

解决Angular中多层嵌套JSON数据的经纬度展示问题

核心解决方案

直接通过链式访问嵌套属性即可获取经纬度,将{{????}}替换为:

纬度: {{result.location.coordinates.latitude}}, 经度: {{result.location.coordinates.longitude}}

完整的HTML代码如下:

<ul *ngIf="customerObs | async as response">
  <li *ngFor="let result of response.results">
    纬度: {{result.location.coordinates.latitude}}, 经度: {{result.location.coordinates.longitude}}
  </li>
</ul>

额外优化建议

  • 避免空指针异常:如果数据可能存在某层属性缺失的情况,使用Angular的安全导航操作符?.:
    纬度: {{result?.location?.coordinates?.latitude}}, 经度: {{result?.location?.coordinates?.longitude}}
    
  • 简化模板逻辑:如果需要频繁访问这些深层属性,可在TS中提前映射处理数据:
    import { map } from 'rxjs';
    
    customerObs = this.http.get<Response>('https://randomuser.me/api/?format=json').pipe(
      map(res => res.results.map(item => ({
        latitude: item.location.coordinates.latitude,
        longitude: item.location.coordinates.longitude
      })))
    );
    
    对应的模板可以简化为:
    <ul *ngIf="customerObs | async as coordsList">
      <li *ngFor="let coord of coordsList">
        纬度: {{coord.latitude}}, 经度: {{coord.longitude}}
      </li>
    </ul>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:30:54