Angular从API渲染数据报错:仅允许数组或可迭代对象
问题解决:Error trying to diff '[object Object]'
错误根源
datas被错误赋值为字符串:你将API响应转为JSON字符串后赋值给datas,但*ngFor仅支持遍历数组或可迭代对象,字符串无法被遍历。- 未正确提取API中的数组数据:API返回的是包含
data数组的对象,你直接使用了整个响应对象而非其中的data数组,导致datas是一个不可遍历的对象。 totalLength计算错误:res是对象,不存在length属性,正确的总条数应该从res.meta.pagination.total获取。
修正后的home.component.ts代码
import { Component, OnInit } from '@angular/core'; import { DataService } from 'src/app/services/data.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { datas:any=[]; errores:string=""; totalLength:any; constructor(private data: DataService) { } ngOnInit(): void { this.data.getMemes().subscribe(res=>{ // 提取响应中的data数组赋值给datas this.datas = res.data; // 从meta中获取总条数 this.totalLength = res.meta.pagination.total; }, error =>{ console.log(error); if(error.status == 0){ this.errores="Código del error: "+error.status+" \n Ha ocurrido un error del lado del cliente o un error de red."; }else{ this.errores="Código del error: "+error.status+"\n\n"+error.statusText; } }) } }
模板额外注意事项
你模板中的图片路径data.attributes.image.data.attributes.url在提供的API响应中不存在,每个data.attributes里没有image字段。请确认API是否返回图片数据,若返回则调整路径,否则需要移除该图片标签或处理空值情况,比如:
<img mat-card-image *ngIf="data.attributes.image?.data?.attributes?.url" [src]="data.attributes.image.data.attributes.url" alt="meme">
内容的提问来源于stack exchange,提问作者Luis Alejandro López de Anda
相关产品推荐
相关产品推荐

