首页 > 解决方案 > 错误找不到“对象”类型的不同支持对象“[对象对象]”

问题描述

我是 Angular 8 的新手,我正在尝试实现一项服务以将数据格式JSON加载到API

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

我也一直在阅读有关此错误的类似问题,但我无法解决它

这是我进行服务调用的 .ts 代码

@Injectable({
  providedIn : 'root'
})
export class CarsService {

  private CarURL = 'https://catalogo-autos.herokuapp.com/api/autos';

  constructor(private http: HttpClient) { }

 getCars(): Observable<Car[]>{

   return this.http.get<Car[]>(this.CarURL);

 }
}

这是服务:

  ngOnInit() {

    this.getCars();
  }

  getCars(): void {

    this.carService.getCars().subscribe((carsTemp)=>{
      this.cars = carsTemp;
    })
  }

最后这是我的HTML标记

<ng-container *ngFor="let car of cars">
    <div class="cars">
        <div class="fas fa-eye" (click)="onSelect(car,infAuto)"></div>
        <div>{{car.description}} </div>
    </div>
</ng-container>

我将不胜感激任何进一步的帮助

标签: angulartypescriptrestapi

解决方案


您必须访问data您获得的响应属性。你得到的对象不是数组。它是带有一些额外数据的对象,其中一个字段data实际上是您所需的属性。您必须记住,在编译您的打字稿代码后,您将获得 js 并通过解析响应JSON.parse(请注意,当某些字段是 fe 类型时Date


推荐阅读