Angular 8 - 创建从 POST 请求返回的 JSON Keys/values 的列表

Angular 8 - Create Lists of JSON Keys/values Returned from POST Request

我想做的就是:

-get the "monthYear" from my JSON response -> set them to a list variable named xValues

-get the "numSessionIds" from my JSON response -> set them to a list variable named yValues

我的 JSON 回复:(我添加了一些新行和空格以便在 post 中更容易阅读):

[
    {
        "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));

如果POST

callNumberOfSessionsSP():any {
    const dataToPost = {startDate:'2020-01-01', endDate:'2022-01-01', frequency: 'monthly'}
    return this.http.post(`${this.BASE_URL}/RESTAPI/reports/callNumberOfSessionsSP`, dataToPost, this.httpOptions);
}

如果是 GET

callNumberOfSessionsSP():any{
    return this.http.get(`${this.BASE_URL}/RESTAPI/reports/callNumberOfSessionsSP?startDate=2020-01-01&endDate=2022-01-01&frequency=monthly`, this.httpOptions);
}

在你的chart.component.ts

ngOnInit() {
    this.chartData = this.chartService.callNumberOfSessionsSP().subscribe(data => {
        console.log(data); /* <-- will have the whole response */
        this.xValues = data.map(a => a.monthYear); //--> ["Jan 20", "Feb 20", "Mar 20"]
        this.yValues = data.map(a => a.numSessionIds); //--> [2, 5, 0]
    });
}

下面是我如何根据 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);

    }

chart.service.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 循环来遍历每个 JSON 组的 3 个值(monthYear、numSessionIds、monthInDateFormat)和 [i] 索引。这允许我执行 .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);
}