Reputation: 77
I am trying to get data from an API, when I console.log() it , I am getting the data in console, but when I try to get it in my table , I am getting following error: ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
my ts file
CovidPatients:any=[];
show() {
this.http.get('https:API-URL').subscribe(responseData=>{
const data1=JSON.stringify(responseData)
this.CovidPatients=JSON.parse(data1)
console.log(data1);
})
}
html
<tr *ngFor="let data of CovidPatients">
<td>{{data.agebracket}}</td>
<td>{{data.contractedfromwhichpatientsuspected}}</td>
<td>{{data.currentstatus}}</td>
<tr>
In the API the data is in nested Array , I think that might be the problem:
{
"raw_data": [
{
"agebracket": "",
"contractedfromwhichpatientsuspected": "",
"currentstatus": "Hospitalized",
"dateannounced": "10/05/2020",
"detectedcity": "",
"detecteddistrict": "",
"detectedstate": "",
"entryid": "",
"gender": "",
"nationality": "",
"notes": "",
"numcases": "2",
"patientnumber": "37900",
"source1": "https://twitter.com/ANI/status/1259331384851775488?s=09",
"source2": "",
"source3": "",
"statecode": "RJ",
"statepatientnumber": "",
"statuschangedate": "",
"typeoftransmission": ""
},
{
"agebracket": "",
"contractedfromwhichpatientsuspected": "",.....................
How to display the data in the table.
Upvotes: 0
Views: 482
Reputation: 2327
JSON.stringify
and JSON.parse
both are unrequired if and only if you are getting the JSON object in response. In *ngFor
you can iterate the array of object if you are not using a keyvalue
pipe.
In your JSON object raw_data
is array so you can try like this
<tr *ngFor="let data of CovidPatients.raw_data">
{{data.agebracket}}
.
.
.
</tr>
Upvotes: 1
Reputation: 980
You can do the following,
show() {
this.http.get('https:API-URL').subscribe(responseData => {
this.CovidPatients = responseData['raw_data']
console.log(this.CovidPatients);
})}
Then inside your template file, you can iterate through the array using *ngFor structural directive,
<tbody *ngFor="let data of CovidPatients">
<tr>
<td>{{data.agebracket}}</td>
<td>{{data.contractedfromwhichpatientsuspected}}</td>
<td>{{data.currentstatus}}</td>
</tr>
<tbody>
Upvotes: 1
Reputation: 935
CovidPatients
is not an array. Change your for loop to this:
<tr *ngFor="let data of CovidPatients.raw_data">
Upvotes: 1