【问题标题】:ERROR Cannot find a differ supporting object '[object Object]' of type 'object'错误找不到“对象”类型的不同支持对象“[对象对象]”
【发布时间】:2020-07-07 14:12:57
【问题描述】:

我是 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>

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

【问题讨论】:

    标签: angular typescript rest api


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      加载 API,看起来所需的汽车数组实际上在 data 属性中。

      在将 observable 返回给控制器之前,您可以将结果映射到 data 属性。试试下面的

      服务

      @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).pipe(map(response => response.data));
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-22
        • 2018-10-12
        • 2018-02-10
        • 2021-03-17
        • 1970-01-01
        • 2020-11-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多