json - Angular html,如何为嵌套对象进行 ngfor 循环?

标签 json angular typescript

我的服务器中有一个这样的对象;

{
    "NBA": {
        "link": "https://www.nba.com/",
        "ticketPrice": 50
    },
    "UEFA": {
        "link": "https://www.uefa.com/",
        "ticketPrice": 39
    },
    "CL": {
        "link": "https://www.uefa.com/uefachampionsleague/",
        "ticketPrice": 76
    },
    "EuroLeague": {
        "link": "https://www.euroleague.net/",
        "ticketPrice": 42
    }
}

我用这段代码订阅了这个对象;

sportsObject : Sports[] //THIS IS THE MEMBER THAT SHOULD BE FILLED WITH THE JSON OBJECT GIVEN
object = Object;
ngOnInit(){
    this.SportsService.getPrices().subscribe(data=>{
      this.sportsObject = data;
    })    
}

这是我的html代码;

   <div *ngFor="let key of Object.keys(sportsObject)">
       <p>The {{key}} is {{{{sportsObject[key]}}</p>
   </div>

但我收到“找不到类型为‘object’的不同支持对象‘[object Object]’”。错误。我怎样才能正确地迭代这个 JSON 对象?

最佳答案

*ngFor 指令默认支持像数组这样的可迭代对象。在这里你可以尝试使用 keyvalue管道 (Angular v6.1.0+ ) 迭代对象。尝试以下操作

<div *ngFor="let sport of sportsObject | keyvalue">
  <p>The {{ sport.key }} is {{ sport.value.ticketPrice }}</p>
  <p>More Info: <a [attr.href]="sport.value.link">{{ sport.value.link }}</a></p>
</div>

另外作为旁注,通常最好避免在指令绑定(bind)中调用函数([dir]="someFunc()"*dir="someFunc()") 和插值 ({{ someFunc() }})。原因是,如果您不控制变更检测策略,那么每个 CD 周期都会触发这些函数,并可能导致性能问题。

关于json - Angular html,如何为嵌套对象进行 ngfor 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63506178/

相关文章:

php - 无法读取数据,因为它的格式不正确 Xcode 11

python - POST 请求 Python 的嵌套字典到 JSON

json - 来自字符串字段的 AWS Athena json_extract 查询返回空值

ios - Angularfire2 FirebaseListObservable 在 iOS 上加载缓慢

angular - 如何从 Angular 将图像作为 blob 发送?

unit-testing - Karma with Typescript - 无法获得代理来提供我的文件(或者我找不到它)

Python2 json : load using strings instead of unicode

Angular 自定义样式到 mat-dialog

javascript - 如何在组件中监听 redux Action 流

typescript - 尝试访问 AVPlaybackStatus 的错误属性时出错