Once Again NgFor 仅支持绑定到 Iterables,例如 Arrays

Once Again NgFor only supports binding to Iterables such as Arrays

和我之前一样,我遇到了这个错误:

Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

我尝试了很多解决方案,例如: error display in *ngfor json array object

但没有任何效果。

  public getInterfaces(): Observable<InterfaceBrief[]> {
    let headers = this.createBasicHeaders();
    let options = new RequestOptions({
      method: 'get',
      headers: headers});
    let url = this.restApi +"/dashboard/list";
    console.log(url);
    return this.http.get(url, options)
      .map(this.extractData)
      .catch(this.handleError);
  }

  private extractData(res: Response) {

    let body = res.json();
    console.log("GOOD");
    return body.data || {};
  }

export class DashboardComponent implements OnInit {

  errorMessage: string;
  interfacesBrief: InterfaceBrief[];

  constructor(private _service: AuthService, private _emotService: EmotClientService) {
  }
  ngOnInit() {
    this.getInterfaces();
  }
  getInterfaces() {
    this._emotService.getInterfaces().subscribe(

      data => this.interfacesBrief = data,
      error => this.errorMessage = <any>error
    );
  }
}

当我改变时:

    return body.data || {}; 

至:

return body.data.items || {};

我有错误:

Cannot read property 'items' of undefined

错误:无法读取未定义的 属性 'data'

  • return 仅 res.json() (为什么有时如果没有正确获取数据,angular 会在此处抛出错误)。

  • 尝试在HTML中使用猫王运算符(安全导航)。

试试这个代码

  private extractData(res: Response) {

    let body = res.json();
    console.log("GOOD");
    return body || {};
  }

  export class DashboardComponent implements OnInit {
   ...............

  getInterfaces() {
    this._emotService.getInterfaces().subscribe(

      data => {
        this.interfacesBrief = data
        console.log(this.interfacesBrief ,"Without Error")
      },
      error => this.errorMessage = <any>error
    );
  }
}

<div *ngFor='let items of interfacesBrief?.data?.items'>
  {{items}}
</div>

根据评论,当您 console.log 您的回复:Array[2] 0 : Object 1 Object client: "client1" countKO: 3 (...) 您的回复中显然没有 data 对象,因此您应该 return按原样回复。

private extractData(res: Response) {
  let body = res.json();
  return body || []; // here!
}

当您收到回复后,您只需迭代该数组并显示您想要的属性,就像这样:

<div *ngFor='let item of interfacesBrief'>
  {{item.client}} - {{item.countKO}} 
  <!-- print whatever else properties you have and want to display -->
</div>