如何在ngFor中使用嵌套的json对象

时间:2019-04-12 13:55:12

标签: json angular loops ngfor

我在遍历json对象以显示消息时遇到问题。 情况是,我将from_id发送到to_idjsonData的消息如下:

jsonData={
    "chat":
    {
        "79":
        {
            "from":"Testing Page - joe",
            "from_id":79,
            "to":"userTestName",
            "to_id":1548,
            "unread":2,
            "messages":
            [
                {"id":154,"page_id":79,"user_id":1548,"text":"this is the first message to be sent by joe","seen":0,"isgroup":0,"group_id":null,"created_at":"2019-04-10 13:54:10","updated_at":"2019-04-10 13:54:10"},
                {"id":155,"page_id":79,"user_id":1548,"text":"this is the second message sent to joe","seen":0,"isgroup":0,"group_id":null,"created_at":"2019-04-11 12:37:39","updated_at":"2019-04-11 12:37:39"}
            ]
        },
        "44":
        {
            "from":"Rock Music Band",
            "from_id":44,
            "to":"userTestName",
            "to_id":1548,
            "unread":1,
            "messages":
            [
                {"id":156,"page_id":44,"user_id":1548,"text":"Hello this message from rock","seen":0,"isgroup":0,"group_id":null,"created_at":"2019-04-11 13:18:44","updated_at":"2019-04-11 13:18:44"}
            ]
        }
    },
    "unread":3
}

我遇到一个问题,无法使用角度<ul>*ngFor中显示这些消息:

  <ul>
    <li *ngFor="let messageData of jsonData.chat;>
      <div class="message-info">
        <h4>{{messageData.from}}</h4>
        <h4>{{messageData.messages[0].text}}</h4>
      </div>
    </li>
  </ul>

我收到了不支持的对象的错误。

  

错误错误:找不到其他支持对象'[对象对象]'   类型为“对象”。 NgFor仅支持绑定到Iterables,例如   数组。

为了显示消息,我的jsonData应该是什么样的?我希望每个id 79-'44'是一个单独的对象。

2 个答案:

答案 0 :(得分:2)

jsonData是一个对象,而不是数组,因此是错误。您可能要使用KeyValuePipe

<ul>
  <li *ngFor="let data of jsonData.chat | keyvalue>
    <div class="message-info">
      <h4>{{jsonData.chat[data.key].from}}</h4> <!-- Or even better: data.value.from -->
      <h4>{{jsonData.chat[data.key].messages[0].text}}</h4> <!-- Or even better: data.value.messages[0].text -->
      <!-- Want to loop through your messages? -->
      <ul>
        <li *ngFor="let message of data.value.messages">{{message.text}}</li>
      </ul>
    </div>
  </li>
</ul>

尽管将数据转换为数组可能是值得的。

答案 1 :(得分:0)

您必须将json格式化为Array才能使ngFor正常工作, 我认为这是您要寻找的: https://stackblitz.com/edit/angular-h7ezpn?file=src%2Fapp%2Fapp.component.ts

$date=$_GET['date'];
$query=mysql_query("select * from product_sold where date=" . $date);
while($lihat=mysql_fetch_array($query)){
    $pdf->Cell(1, 0.8, $no , 1, 0, 'C');
    $pdf->Cell(3, 0.8, $lihat['date'],1, 0, 'C');
    $pdf->Cell(6, 0.8, $lihat['product'],1, 0, 'C');
    $pdf->Cell(3, 0.8, $lihat['quantity'], 1, 0,'C');
    $pdf->Cell(4, 0.8, "Rp. ".number_format($lihat['price'])." ,-", 1, 0,'C');