Reputation: 1710
I am using ng2-smart-table and trying to display data
When I create a local array of objects like:
var data = [
{
id: 1,
name: 'Leanne Graham',
username: 'Bret',
email: '[email protected]',
},
{
id: 2,
name: 'Ervin Howell',
username: 'Antonette',
email: '[email protected]',
},
{
id: 3,
name: 'Clementine Bauch',
username: 'Samantha',
email: '[email protected]',
}
]
it works but when I receive json result like from my API it doesn't work:
data = [
0:{
id: 1,
name: 'Leanne Graham',
username: 'Bret',
email: '[email protected]',
},
1:{
id: 2,
name: 'Ervin Howell',
username: 'Antonette',
email: '[email protected]',
},
2:{
id: 3,
name: 'Clementine Bauch',
username: 'Samantha',
email: '[email protected]',
}
]
Any ideas?
Upvotes: 0
Views: 305
Reputation: 39432
Both the structures that you've shared in the question are completely different. Ideally, it would be better if you have the same response structure coming in from your API. I think the first one is the structure in which your API is responding. I'm not really sure how come you got the below structure. It isn't a valid Array anyway.
If you're still getting this response, you can create a mapping function to make this work. Here's how:
Assuming that here's the sort of response that you're getting from your API:
data = {
'0': {
id: 1,
name: 'Leanne Graham',
username: 'Bret',
email: '[email protected]',
},
'1': {
id: 2,
name: 'Ervin Howell',
username: 'Antonette',
email: '[email protected]',
},
'2': {
id: 3,
name: 'Clementine Bauch',
username: 'Samantha',
email: '[email protected]',
}
}
You can convert it into a data of the required format like this:
let myData = [];
for(let index in data) {
myData.push(data[index]);
}
UPDATE This data looks familiar. Are you using JSONPlaceholder? Coz if that's the case, you can have a look at this Sample StackBlitz Project that I've created. I'm also using JSONPlaceholder API to get the users list and show it on an Angular Material Table. This sample should help you understand how to get the response from an API.
Upvotes: 1