首页 > 解决方案 > 尝试区分“[object Object]”时出错。角度中只允许使用数组和可迭代对象

问题描述

我正在尝试在前端显示数据,但出现上述错误。如何解决这个问题?

服务.ts

rec_source(){
    var headers = new HttpHeaders().set('Authorization', 'Token ' + localStorage.getItem('usertoken'));
    headers.append('Accept', 'application/json');
    var options =  {
      headers: headers
  };
  return this.httpClient.get('api/recruit/fetch_recruitment_details',options)
  }

组件.ts

sources:any = [];

constructor(private Authentication:AuthService) { }

ngOnInit() {

this.Authentication.rec_source()
  .subscribe(source => {
    this.sources = source;
  });
}

组件.html

<table *ngIf="sources" class="row-border hover">
<thead>
  <tr>
    <th>Data</th>
  </tr>
</thead>
<tbody>
  <tr *ngFor="let source of sources">
    <td>{{ source}}</td>
  </tr>
</tbody>
</table>

//需要显示的数据

需要显示的数据

//错误 错误

标签: angularangular5angular6

解决方案


您的 api 响应不是数组或可迭代的,即错误所说的。它是对象,不能用 迭代*ngFor。也许您想迭代data_candidate_sourcedata_new_hiredate. 在这种情况下,您需要为source组件中的属性分配正确的属性:

this.sources = source.data_candidate_source

或者当您想遍历对象时,您可以使用新添加的键值管道


推荐阅读