首页 > 解决方案 > Angular:显示 InfluxDB API 的结果

问题描述

我收到返回以下数据的InfluxDB API 。我需要在 Angular 的表格中显示这些数据,但我不知道该怎么做。我应该把它当作一个对象吗?或者作为一个数组?有谁知道有没有例子?我的 Angular 版本是 9。

零件:

            listaCBS_CPU: listaCBSCPU = new listaCBSCPU(); //definition

            listadoCBS_CPU(){   
                this.cbsServicio.getListadoCBS_CPU ()
                .subscribe( (respuesta:any) => {
                this.listaCBS_CPU = respuesta;
                });
            }

服务 cbsServicio.service.ts:

            getListadoCBS_CPU(){
                return this.httpClient.get(`${this.PHP_API_SERVER_INFLUX}&q=SELECT * FROM "apache" WHERE ("host" = \'ax14565.com\') fill(null) LIMIT 3`);
            }

结果console.log:

{
  "results": [
    {
        "statement_id": 0,
        "series": [
            {
                "name": "apache",
                "columns": [
                    "time",
                    "host",
                    "BusyWorkers",
                    "server"
                ],
                "values": [
                    [
                        "2020-08-19T07:41:40Z",
                        "775.com",
                        2,
                        "localhost"
                    ],
                    [
                        "2020-08-19T07:41:50Z",
                        "633775.com",
                        2,
                        "localhost"
                    ],
                    [
                        "2020-08-19T07:42:00Z",
                        "oc103.com",
                        2,
                        "localhost"
                    ]
                ]
            }
        ]
    }
  ]
}

为了查看“值”的结果,我应该如何在 HTML 中显示它?

标签: jsonangularinfluxdb

解决方案


convertData(columns:string[], data[]){
  const data = []
  for (let i = 0; i < data.length; i++){
    const tmp = {}
    for (let j = 0; j < columns.length; j++)
      tmp[columns[j]] = data[i][j];
    data.push(tmp)
  }
  return (data);
}

...

listaCBS_CPU: listaCBSCPU = new listaCBSCPU(); //definition

listadoCBS_CPU(){   
  this.cbsServicio.getListadoCBS_CPU()
    .subscribe( (respuesta:any) => {
       this.listaCBS_CPU = respuesta;
       this.dataSource = this.convertData(respestua[0].series.columns, respestua[0].series.values
    });
  }

在你的 html

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <!--- Note that these columns can be defined in any order.
        The actual rendered columns are set as a property on the row definition" -->

  <!-- Time Column -->
  <ng-container matColumnDef="time">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.time}} </td>
  </ng-container>
...
</table>

您只需要将整个 json 转换为有效dataSource

还要考虑一个变量来保存你的列名。

其余的请遵循本教程


推荐阅读