JSON 响应在数组中,但仍然抛出错误 "NgFor only supports binding to Iterables such as Arrays"

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

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>

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

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 将是未定义的,因此 angular 会抱怨。

 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>