JSON in Angular 6

0

I'm having a problem handling Json in Angular.

The Json is:

{
    "0": {
        "id": "2287947",
        "chattime": "1544102153",
        "chat": "Finalizado",
        "chattype": "text",
        "media": "",
        "outgoing": "0",
        "bot": "0",
        "unread": "1",
        "email_created": ""
    },
    "1": {
        "id": "2287931",
        "chattime": "1544102141",
        "chat": "asdasdasd",
        "chattype": "text",
        "media": "",
        "outgoing": "1",
        "bot": "0",
        "unread": "0",
        "email_created": "api"
    }
}

And in Angular's html I have a for

<div *ngFor="let chat of chats">
{{chat.id}}
</div>

But he tells me this error:

ERROR Error: "Can not find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

Thanks

    
asked by Spyros Capetanopulos 10.12.2018 в 22:00
source

1 answer

1

The problem you have is that angular does not allow you to iterate in the template an object, but it must be an array, for this you have the following:

chats= {
    "0": {
        "id": "2287947",
        "chattime": "1544102153",
        "chat": "Finalizado",
        "chattype": "text",
        "media": "",
        "outgoing": "0",
        "bot": "0",
        "unread": "1",
        "email_created": ""
    },
    "1": {
        "id": "2287931",
        "chattime": "1544102141",
        "chat": "asdasdasd",
        "chattype": "text",
        "media": "",
        "outgoing": "1",
        "bot": "0",
        "unread": "0",
        "email_created": "api"
    }

chats = Object.keys(chats).map(e=>chats[e]);

If you print the value, you can see that the "key" of the JSON are converted into an array, and in the template they can be iterated without any problem.

I hope it serves you.

Source or Reference

  

link

    
answered by 10.12.2018 / 22:36
source