【问题标题】:how to go through json result without using ngFor angular如何在不使用 ngFor angular 的情况下通过 json 结果
【发布时间】:2020-08-24 15:10:44
【问题描述】:

我有 JSON 结果,我从后端得到它,它给了我以下结果

[
   {
      "status":"RUN",
      "numberOfTurbines":1
   },
   {
      "status":"ERROR",
      "numberOfTurbines":20
   },
   {
      "status":"STOP",
      "numberOfTurbines":5
   },
   {
      "status":"START_UP",
      "numberOfTurbines":2
   }
]

我有 4 张带有图标的卡片,这些图标指示我的 ts 组件中的每个状态(运行、错误、停止、启动):

this.service.getAllTurbinesStat().subscribe(s=>{
  this.allStats = s;
});

在我的 html 中:

<div class="row">
<div class="d-flex justify-content-start">
<mat-card class="cards">
   <mat-card-title style="color:red;">RUN</mat-card-title>
</mat-card>
<mat-card  class="cards">
   <span class="material-icons">
     pan_tool
   </span>
   <mat-card-title>ERROR</mat-card-title>
</mat-card>
<mat-card  class="cards ">
   <span class="material-icons">
   build_circle
   </span>
   <mat-card-title>STOP</mat-card-title>
</mat-card>
<mat-card  class="cards">
   <span class="material-icons" >
     arrow_circle_down
   </span>
   <mat-card-title>Start_up</mat-card-title>
</mat-card>

我只想获取各自的数据并放入每张卡,我该如何实现?*ngFor我知道通过数据但是我怎样才能获得我想要的字段数据?numberOfTurbines和状态

【问题讨论】:

  • 如果你确定你只会得到这些数据。然后使用状态(不需要)对结果进行排序并使用索引显示数据。前任。 this.allStats[0].status 将返回 RUN,this.allStats[0].numberOfTurbines 将返回 1。
  • @HPSingh 我不需要 ngFor 吗?
  • 是的,你不需要 ngFor。您将按索引从数组“this.allStats”中获取数据。
  • @SamScholefield 的答案看起来是正确的。

标签: angular


【解决方案1】:

你为什么不使用*ngFor

const turbines = [] // your array of JSON objects
<div *ngFor="let turbine of turbines">
  <mat-card>
    <p>Status: {{ turbine.status }} </p>
    <p>Turbines: {{ turbine.numberOfTurbines }}</p>
  </mat-card>
</div>

【讨论】:

    猜你喜欢
    • 2018-02-13
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 2013-12-25
    • 2017-06-08
    • 2021-02-04
    相关资源
    最近更新 更多