2
votes

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.

Object is array

1
company and comp are different!Priyesh Kumar
@PriyeshKumar updated the change.bashIt

1 Answers

2
votes

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>