Hi I'm having an issue while trying to display the data received from my API call into an HTML table using angular2.
I am trying to display the name of each group I receive from backend in a table.
From console log, I can see that my data is in the following format:
{
"list":[
{"group_uuid":"26750058-eda0-448b-a4ff-bedf5f7c70e1","name":"Group 2","description":null},
{"group_uuid":"2f95cebc-7cc2-4c31-bc05-75890e8fee35","name":"group 6","description":null},
{"group_uuid":"3eb5a9f6-4ad7-4757-a0f7- f533bbcbcece","name":"Group1","description":null}
]
}
Based off of other answers, I have tried this:
<tr *ngFor="let item of grouplist.list">
<td>{{item.name}}</td>
</tr>
^ The above says 'List not found' as an error.
If I try:
<tr *ngFor="let item of grouplist">
<td>{{item}}</td>
</tr>
It prints the raw JSON data in the table once and that is all (looks the same as console log).
Any suggestions?
You have to parse the string
to an Object
. For that, use JSON.parse()
I leave the working StackBlitz
If you are using Http Module while receiving , you have to call JSON.Pars();
in the service file:
// HttpModule
getRequest(url): Observable<any> {
return this.http.get(url).map(this.extractData);
}
private extractData(response: Response) {
const body = response.json();
return body.data || {};
}
if you are using Http Client Module no need to call JSON.Pars();
// Http Clinet Module
getRequest(url: string): Observable<any> {
return this.http.get(url);
}
For example :
export interface Instance {
group_uuid: string;
name: string;
description: string;
}
in your component
groupList: Instance[] = [];
ngOnInit(): void {
this.YOURSERVICENAME.getRequest(URL)
.subscribe(response => {
this.groupList = response.list as Instance[];
}, error => {
alert('error');
});
}
in your component.html
<table>
<tr *ngFor="let item of groupList">
<td>
{{item.group_uuid}}
</td>
<td>
{{item.name}}
</td>
<td>
{{item.description}}
</td>
</tr>
</table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.