【问题标题】:Angular 5 and json formatting -> not well formattedAngular 5 和 json 格式 -> 格式不正确
【发布时间】:2018-11-22 20:32:21
【问题描述】:

我有一个带有 json 对象的数组

msgBodyDetailArr = [
    {
      Body: [
        { Id: 1, Name: 'Tomato Soup', Category: 'Groceries', Price: 1.0 },
        { Id: 2, Name: 'Yo-yo', Category: 'Toys', Price: 3.75 },
        { Id: 3, Name: 'Hammer', Category: 'Hardware', Price: 16.99 }
      ]
    }
  ];

现在我想在我的 Angular 应用中查看这个,所以我创建了一个非常简单的页面:

<div class="list-group" *ngFor="let item of msgBodyDetailArr; let i=index">
  <div class="list-group-item">
    <h4 class="list-group-item-heading"> Message body </h4>
    <p class="list-group-item-text"> {{item.Body | json }} </p>
  </div>
</div>

我尝试使用 json 管道中的构建,但视图的输出是这样的:

邮件正文 [ {“Id”:1,“名称”:“番茄汤”,“类别”:“杂货”,“价格”:1 },{“Id”:2,“名称”:“Yo-yo”,“类别”:“玩具”、“价格”:3.75 }、{“Id”:3、“名称”:“锤子”、“类别”:“硬件”、“价格”:16.99 } ]

有没有办法让它像这样格式化?

{ Id: 1, Name: 'Tomato Soup', Category: 'Groceries', Price: 1.0 },
{ Id: 2, Name: 'Yo-yo', Category: 'Toys', Price: 3.75 },
{ Id: 3, Name: 'Hammer', Category: 'Hardware', Price: 16.99 }

非常感谢, 利诺

【问题讨论】:

  • JSON pipe 只是根据窗口大小将数据重新转换为json 格式,如果您需要将数据美化为DOM,则应该对其进行迭代

标签: json angular


【解决方案1】:

你可以试试这个解决方案

使用&lt;pre&gt;标签

<div class="list-group" *ngFor="let item of msgBodyDetailArr; let i=index">
  <div class="list-group-item">
    <h4 class="list-group-item-heading"> Message body </h4>
    <pre class="list-group-item-text"> {{item.Body | json }} </pre>
  </div>
</div>

<div class="list-group" *ngFor="let item of msgBodyDetailArr">
  <div class="list-group-item">
    <h4 class="list-group-item-heading"> Message body </h4>
    <p class="list-group-item-text" *ngFor="let singleObj of item.Body">{{singleObj | json }}</p>
  </div>
</div>

【讨论】:

    【解决方案2】:

    如果要显示数组的对象,则必须迭代 Body 数组。为此,您必须再使用一次*ngFor 来迭代Body 数组。

    <div class="list-group" *ngFor="let item of msgBodyDetailArr">
      <div class="list-group-item">
        <h4 class="list-group-item-heading"> Message body </h4>
        <p class="list-group-item-text" *ngFor="let obj of item.Body">{{obj | json }}</p>
      </div>
    </div>
    

    【讨论】:

      【解决方案3】:

      作为它的数组,你可以这样尝试

        <p class="list-group-item-text" *ngFor="let member of item.Body">
           {{member | json }} </p>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        相关资源
        最近更新 更多