首页 > 解决方案 > Angular 8 - 创建从 POST 请求返回的 JSON 键/值列表

问题描述

我要做的就是:

- 从我的 JSON 响应中获取“monthYear” -> 将它们设置为名为xValues的列表变量

- 从我的 JSON 响应中获取“numSessionIds” -> 将它们设置为名为yValues的列表变量

我的 JSON 响应:(我添加了一些新的行和空格,以便在这篇文章中更容易阅读):

[
    {
        "monthYear": "Jan 20",
        "numSessionIds": 2,
        "monthInDateFormat": 1577768400000
    },
    {
        "monthYear": "Feb 20",
        "numSessionIds": 5,
        "monthInDateFormat": 1580446800000
    },
    {
        "monthYear": "Mar 20",
        "numSessionIds": 0,
        "monthInDateFormat": 1582952400000
    }
]

我通过在chart.service.ts中调用这个函数来获取这些数据:

httpOptions = {
    headers: new HttpHeaders({ 
      'Content-Type': 'application/json',
       credentials: 'same-origin',
     }),
  };

callNumberOfSessionsSP():any{
    return this.http.post(`${this.BASE_URL}/RESTAPI/reports/callNumberOfSessionsSP?startDate=2020-01-01&endDate=2022-01-01&frequency=monthly`,
      this.httpOptions,{responseType: 'json', observe: 'response'}).subscribe()
  }

构造函数和初始变量名称(chart.component.ts):

  chartData: any;
  xValues: any;
  yValues: any;

  constructor(private chartService:ChartService) { }

我的 ngOnInit 方法(chart.component.ts):

ngOnInit() {
    this.chartData = this.chartService.callNumberOfSessionsSP();

    this.xValues = ??????
    this.yValues = ??????
}

这 ??????是我不确定该放什么的地方。我已经尝试过类似的事情:

this.xValues=this.chartData.monthYear;

this.xValues=JSON.parse(Object.keys(this.chartData));

标签: jsonangularparsingpostangular8

解决方案


以下是我从 JSON 响应创建 xValues 和 yValues 列表的方法:

chart.component.ts:

    xValues: string[] = [];
    yValues: number[] = [];

    constructor(private chartService: ChartService) {
        this.chartService.callNumberOfSessionsSP().subscribe((data: any) => {
            //console.log(data[0].monthYear);
            for (let i = 0; i < data.length; i++) {
                console.log(data[i].monthYear);
                this.xValues.push(data[i].monthYear);
                this.yValues.push(data[i].numSessionIds);
            }
            



        console.log("printing this.xValues: ");
        console.log(this.xValues);

        console.log("printing this.yValues: ");
        console.log(this.yValues);

    }

图表服务.ts:

callNumberOfSessionsSP(): any {
        return this.http.post(`${this.BASE_URL}/RESTAPI/reports/callNumberOfSessionsSP?startDate=2021-01-01&endDate=2021-05-01&frequency=monthly`,
            this.httpOptions).pipe(
                map((data: []) => {
                    return data;
                }), catchError(error => {
                    console.log(error);
                    return throwError('Error occurred while calling api of name "callNumberOfSessionsSP"');
                })
            )
    }

说明

我基本上只需要下面的 for 循环来使用 [i] 索引遍历每个 JSON 集的 3 个值(monthYear、numSessionIds、monthInDateFormat)。这使我可以使用 .monthYear 和 .numSessionIds 来获取 json 响应中特定键的特定列/值。

在我尝试 data.monthYear 之前,我只需要执行 data[i].monthYear。

for (let i = 0; i < data.length; i++) {
    console.log(data[i].monthYear);
    this.xValues.push(data[i].monthYear);
    this.yValues.push(data[i].numSessionIds);
}

推荐阅读