0

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: 'Sincere@april.biz',
  },
  {
    id: 2,
    name: 'Ervin Howell',
    username: 'Antonette',
    email: 'Shanna@melissa.tv',
  },
  {
    id: 3,
    name: 'Clementine Bauch',
    username: 'Samantha',
    email: 'Nathan@yesenia.net',
  }
]

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: 'Sincere@april.biz',
  },
  1:{
    id: 2,
    name: 'Ervin Howell',
    username: 'Antonette',
    email: 'Shanna@melissa.tv',
  },
  2:{
    id: 3,
    name: 'Clementine Bauch',
    username: 'Samantha',
    email: 'Nathan@yesenia.net',
  }
]

Any ideas?

Denis Evseev
  • 1,660
  • 1
  • 18
  • 33
  • Please add your API details and some code to see how it's not working. If possible, also add a StackBlitz link to a sample. – SiddAjmera Aug 27 '18 at 17:09

1 Answers1

1

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: 'Sincere@april.biz',
  },
  '1': {
    id: 2,
    name: 'Ervin Howell',
    username: 'Antonette',
    email: 'Shanna@melissa.tv',
  },
  '2': {
    id: 3,
    name: 'Clementine Bauch',
    username: 'Samantha',
    email: 'Nathan@yesenia.net',
  }
}

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.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110