[Fixed] Angular 8 – Create Lists of JSON Keys/values Returned from POST Request

Issue

All I am trying to do is this:

-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

My JSON response: (I added some new lines and spaces to make it easier to read in this post):

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

I get this data by calling this function in 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()
  }

constructor & initial variable names (chart.component.ts):

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

  constructor(private chartService:ChartService) { }

my ngOnInit method (chart.component.ts):

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

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

The ?????? is where I’m unsure what to put. I’ve already tried things like:

this.xValues= this.chartData.monthYear;

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

Solution

Here’s how I created xValues and yValues lists from the JSON response:

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"');
                })
            )
    }

Explanation:

I basically just needed the below for loop to iterate through each JSON set of 3 values (monthYear, numSessionIds, monthInDateFormat) with the [i] index. This allowed me to do .monthYear and .numSessionIds to get specific columns / values of specific keys in the json response.

Before I was trying data.monthYear, but I just needed to do 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);
}

Leave a Reply

(*) Required, Your email will not be published