-1

Estoy con un problema para el manejo de Json en Angular.

El Json es:

{
    "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"
    }
}

Y en el html de Angular le tengo un for

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

Pero me dice este error:

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

Gracias

1 respuesta 1

1

El problema que tienes es que angular no te permite iterar en la plantilla un objeto, si no que debe ser un array, para ello has lo siguiente:

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]);

si imprimes el valor, puedes ver que los "key" del JSON se convierten en array, y en el template pueden iterarse sin problema alguno.

Espero te sirva.

Fuente o Referencia

https://stackoverflow.com/questions/40521167/convert-json-object-in-to-array-to-iterate-through-ng-repeat-using-javascript/40521237

2

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.