【问题标题】:Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor Angular 9找不到“object”类型的不同支持对象“[object Object]”。 NgFor Angular 9
【发布时间】:2021-03-11 17:52:49
【问题描述】:

我尝试了很多解决方案,但没有一个不起作用。请帮我解决这个问题。我需要遍历 JSON 对象。下面是我尝试过的和我的 JSON 代码。我可以在 tr 标签中打印 Section 名称,但我无法在 tr 标签中打印 School 对象名称。

service.ts

  getSections(): Observable<Section> {
     return this.http
      .get<Section>(this.apiUrl + 'sections/all')
      .pipe(
      retry(2),
       catchError(this.handleError),
      );
  }

组件.ts

 getSections() {
  this.service.getSections().subscribe(response => {
  Object.assign(this.sectionData, response);
  console.log(response);
  });
}

component.html

   <table class="table table-hover">
    <thead class="thead-light">
    <tr>
      <th>#</th>
      <th>Section Name</th>
      <th>School Name</th>
    </tr>
    </thead>
    <tr *ngFor="let pro of sectionData ;let i=index">
      <td [hidden]="true">{{pro.sectionID}}</td>
      <td>{{i + 1}}</td>
      <td>{{pro.Name}}</td>
      <ng-container *ngFor="let sch of pro.School">
        <td>{{sch.Name}}</td>
      </ng-container>
    </tr>
  </table>

我的 JSON

[{
"$id": "1",
"SectionID": 1,
"SchoolID": 6,
"Name": "Grade 1",
"Active": true,
"Tstamp": null,
"Classes": [],
"School": {
    "$id": "2",
    "SchoolID": 6,
    "Name": "Yalpanam",
    "AlternativeName": "سصر ءصيص",
    "TelephoneNumber": "16556489",
    "URL": "",
    "EmailID": "",
    "Longitude": null,
    "Latitude": null,
    "Active": true,
    "Tstamp": null,
    "ClassSections": [],
    "NonStaffs": [],
    "Principals": [],
    "Students": []
}
}]

我得到的错误是 Error Msg

【问题讨论】:

    标签: json angular api asp.net-web-api angular9


    【解决方案1】:

    在你的 JSON 中,School 不是一个数组——它是一个对象。所以你不能迭代它。要解决这个问题,请在您的标记更改中:

      <ng-container *ngFor="let sch of pro.School">
        <td>{{sch.Name}}</td>
      </ng-container>
    

    简单

      <td>{{pro.School?.Name}}</td>
    

    【讨论】:

    • 你是救命恩人兄弟。谢谢,我花了 3 天时间寻找解决方案。成功了。
    • 很高兴听到这个消息。记得把这个答案标记为正确的。
    猜你喜欢
    • 2019-09-15
    • 2020-08-09
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2020-10-17
    • 2017-10-15
    相关资源
    最近更新 更多