Search code examples
angularngx-charts

Angular ngx-chart: Object not iterable


I have problem with Anguler ngx-charts. I am trying to plot data and still getting error:
ERROR TypeError: data is not iterable.

If I use this data defined in ts file, plot shows correctly.

public data = [
  {
    "name": "Požadovaný prùtok vzduchu",
    "series": [
      {
        "value": "  923",
        "name": "0"
      },
      {
        "value": "  923",
        "name": "0"
      },
      {
        "value": "  924",
        "name": "1"
      },
      {
        "value": "  916",
        "name": "5"
      },
      {
        "value": "  916",
        "name": "8"
      }
    ]
  }
];

But I need to plot data from https request. My code is:

this.loadedFile.getContent(email,this.nazev).subscribe(res => { 
        console.log(this.data);
        this.data = res.data;
  });
getContent(folder:any, filename:any) {
    return this.httpClient.post<any>(apiUrl + 'loginApi/contentApi/file.php', {folder,filename});  
    }

Result res.data should be JSON with correct format.

"data": {
        "name": "Požadovaný prùtok vzduchu",
        "series": [
            {
                "value": "  923",
                "name": "0"
            },
            {
                "value": "  923",
                "name": "0"
            },
etc...

This is my code and I cannot plot data from request, because of iterable error. I tried convert it to string and back to JSON format, used as string, create array and nothing worked.

Thank you! :)


Solution

  • Use JSON.stringify() and replace() to replace { with [{ and } with }] and JSON.parse() to make into object again.

    let data = {
      "name": "Požadovaný prùtok vzduchu",
      "series": [{  "value": "  923",  "name": "0"},{  "value": "  923",  "name": "0"},{  "value": "  924",  "name": "1"},{  "value": "  916",  "name": "5"},{  "value": "  916",  "name": "8"}
      ]
    };
    console.log(JSON.parse(JSON.stringify(data).replace(/^\{(.*)\}$/,"[ { $1 }]")));
    .as-console-wrapper { max-height: 100% !important; top: 0; }