尝试与'[object Object]'进行比较时出错。只允许数组和可迭代对象成角度

时间:2018-10-29 10:58:43

标签: angular angular5 angular6

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

  

service.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)
  }
  

component.ts

sources:any = [];

constructor(private Authentication:AuthService) { }

ngOnInit() {

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

component.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>

//需要显示的数据

the data that needs to be displayed

//错误 the error

1 个答案:

答案 0 :(得分:1)

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

this.sources = source.data_candidate_source

或者,当您要遍历对象时,可以使用新添加的keyvalue pipe