JSON响应位于数组中,但仍会引发错误"NgFor仅支持绑定到Iterables(如数组)". [英] JSON response is in array but still throws an error "NgFor only supports binding to Iterables such as Arrays"

查看:98
本文介绍了JSON响应位于数组中,但仍会引发错误"NgFor仅支持绑定到Iterables(如数组)".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TypeScript文件

export class CompanyComponent  {
  apiService : APIService;
  data : any;
  private companyUrl = 'http://localhost:4000/api/company/';

  constructor(apiService : APIService) {
    this.apiService = apiService;
    this.getCompanies(this.companyUrl);
  }

  getCompanies(url: any){
    this.data = this.apiService.GET(url).map((response :Response)=>
    response.json()).subscribe((response)=>{
    this.data = response;
    console.log(this.data);
  })
}

响应数组

[
   {"_id":"58f61a132d44240d085ca2fa","comapny_name":"Burslem 
  Spice","__v":1,"categories":["58f643382d44240d085ca2fb"]},<br>
  {"_id":"590487964a45c56c0fa2911a","comapny_name":"Tiger 
  Bite","categories":[]}
]

HTML文件

<div class="media">
  <div class="media-left" >
    <li class="media" *ngFor = "let comp of data" >
      <label>{{comp}}</label>
    </li>   
  </div>  
</div>

上面的响应仍在数组中,但出现此错误:

The above response is still in array but I get this error:

错误是由于:找不到类型为对象"的其他支持对象"[对象对象]". NgFor仅支持绑定到Iterables 例如数组.

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

推荐答案

data : any;说数据可以是任何东西,但是* ngFor仅接受Iterables. 将其更改为array 因为正在加载异步,所以第一次渲染dom时,data将是未定义的,因此会有角度的抱怨.

data : any; says data can be anything, but *ngFor accepts only Iterables. Change it to array Because you are loading async, when first time dom is rendered, data will be undefined and so angular will complain.

 export class CompanyComponent  {
      apiService : APIService;
      data : Array; // or array
      private companyUrl = 'http://localhost:4000/api/company/';

constructor(apiService : APIService) {
        this.apiService = apiService;
        this.getCompanies(this.companyUrl);
        this.data = []
}

getCompanies(url: any){
        this.apiService.GET(url).map((response :Response)=>
        response.json()).subscribe((response)=>{
            this.data = response;
            console.log(this.data);
        })
}

HTML

<div class="media">
  <div class="media-left" >
      <li class="media" *ngFor = "let comp of data" >
          <label> {{comp.company_name}}</label>
      </li>   
  </div>  
</div>

这篇关于JSON响应位于数组中,但仍会引发错误"NgFor仅支持绑定到Iterables(如数组)".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆