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

Angular调用RestCountries API时货币显示[object object]问题

解决Angular中Rest Countries接口货币字段显示[object object]的问题

问题原因

Rest Countries接口返回的currencies是键值对对象(格式类似{"USD": {"name": "美元", "symbol": "$"}}),而非数组,直接插值或错误使用*ngFor会导致显示[object object],另外你之前的代码还存在变量名拼写错误(cur和curr不一致)。

解决方案

使用Angular内置的KeyValuePipe遍历对象的键值对,即可正确获取货币信息:

修正后的HTML代码

<tbody>
    <tr *ngFor="let c of data">
      <td>{{ c.name.common }}</td>
      <td>{{ c.capital?.[0] }}</td> <!-- 部分国家无首都,添加安全导航操作符避免报错 -->
      <td>{{ c.flag }}</td>
      <td>
        <!-- 使用KeyValuePipe遍历currencies对象 -->
        <span *ngFor="let currency of c.currencies | keyvalue; let last = last">
          {{ currency.key }} - {{ currency.value.name }} ({{ currency.value.symbol }})
          <span *ngIf="!last">, </span>
        </span>
      </td>
    </tr>
</tbody>

关键说明

  • KeyValuePipe会把对象转换成{key: 键名, value: 键值}的结构数组,便于遍历
  • 添加?.安全导航操作符,避免部分无首都的国家触发报错
  • 修正了变量名拼写错误,统一使用currency作为遍历变量
  • 可按需调整显示内容,比如只显示名称:{{ currency.value.name }}

可选:组件内预处理数据

如果不想在模板中使用管道,也可以在组件里把currencies转成数组:

// 组件中获取数据后处理
this.yourService.getContrires().subscribe(data => {
  this.data = data.map(country => ({
    ...country,
    // 把currencies对象转为数组
    currenciesArray: Object.entries(country.currencies).map(([code, info]) => ({
      code,
      name: info.name,
      symbol: info.symbol
    }))
  }));
});

之后模板中直接遍历currenciesArray:

<td>
  <span *ngFor="let cur of c.currenciesArray; let last = last">
    {{ cur.code }} - {{ cur.name }} ({{ cur.symbol }})
    <span *ngIf="!last">, </span>
  </span>
</td>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 15:27:09