JSON response is in array but still throws an error “NgFor only supports binding to Iterables such as Arrays”

荒凉一梦 提交于 2020-01-24 14:26:07

问题


TypeScript File

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);
  })
}

Response array

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

HTML file

<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:

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


回答1:


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>


来源:https://stackoverflow.com/questions/43696767/json-response-is-in-array-but-still-throws-an-error-ngfor-only-supports-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!