如何在Angular 6中显示带有更改字符串的嵌套JSON对象

时间:2018-11-18 00:05:00

标签: javascript arrays json angular nested

解决了一个非常棘手的问题,却不知道如何解决。我正在用Angular 6编写代码。

对于我的问题,这是我的JSON文件。我可以轻松访问"id""certificate之类的数据。但是我想显示票证上剩余的嵌套remainingCounts,这是下一个问题:remainingCounts编号之前的ID始终与appointmentTypeIDs匹配。如何告诉我的Angular Frontend始终显示remainingCounts数组中包含的所有数据?

[
   {
      "id":9073111,
      "certificate":"A4245322",
      "productID":425193,
      "appointmentTypeIDs":[
         5780379
      ],
      "remainingCounts":{
         "5780379":10
      }
   },
   {
      "id":9073113,
      "certificate":"0BE0C148",
      "productID":435370,
      "appointmentTypeIDs":[
         5780416
      ],
      "remainingCounts":{
         "5780416":50
      }
   },
   {
      "id":9073115,
      "certificate":"E72984C2",
      "productID":435376,
      "appointmentTypeIDs":[
         5780421
      ],
      "remainingCounts":{
         "5780421":100
      }
   }
]

我的证书。ts:

export class CertificatesComponent implements OnInit {
  private certificates: Array<object> = [];
  pageTitle = 'Meine Zertifikate';
  email = this.auth.userProfile.name;

  constructor(
    private title: Title,
    private apiService: APIService,
    public auth: AuthService
  ) {}

  ngOnInit() {
    this.title.setTitle(this.pageTitle);
    this.getData();
  }

  public getData() {
    this.apiService
      .getCertificatesByUser(this.email)
      .subscribe((data: Array<object>) => {
        this.certificates = data;
        console.log(data);
      });
  }
}

任何我的HTML模板:

<div class="ui cards" *ngFor="let certificate of this.certificates">
      <div class="card">
        <div class="content">
          <div class="header">{{certificate.name}}</div>
          <div class="meta">{{certificate.email}}</div>
          <div class="description">
            Verbleibende Termine Ihrer {{certificate.name}}-Karte:
            <span *ngFor="let remainingCount of certificates.remainingCounts">
              {{remainingCount}}
            </span>
          </div>
        </div>
        <sui-progress class="bottom attached indicating active" [value]="80"></sui-progress>
      </div>
    </div>

1 个答案:

答案 0 :(得分:1)

首先,根据您提供的JSON数据, remainingCounts 不是一个数组。这只是另一个对象。

您可以像其他属性一样使用dot(.)运算符来显示,而无需 ngFor

<div class="ui cards" *ngFor="let certificate of this.certificates"> <div class="card"> <div class="content"> <div class="header">{{certificate.name}}</div> <div class="meta">{{certificate.email}}</div> <div class="description"> Verbleibende Termine Ihrer {{certificate.name}}-Karte:  {{certificate.remainingCount}}  </div> </div> <sui-progress class="bottom attached indicating active" [value]="80"></sui-progress> </div> </div>

STACKBLITZ DEMO