Angular中NgFor绑定对象报错,如何修改代码解决?
Angular错误解决:Cannot find a differ supporting object '[object Object]' of type 'object'
错误信息
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays
相关代码
组件代码
import { HttpClient } from '@angular/common/http'; import { Component, OnInit} from '@angular/core'; import { AnyArray } from 'mongoose'; import { DataService } from '../../services/data.service'; @Component({ selector: 'app-allpatients', templateUrl: './allpatients.component.html', styleUrls: ['./allpatients.component.css'] }) export class AllpatientsComponent implements OnInit { dataArray:any constructor(private ds:DataService){ this.ds.getAllPatients().subscribe(data=>this.dataArray=data); } ngOnInit(): void{ } }
服务代码
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { constructor(private http:HttpClient) { } getAllPatients(){ return this.http.get('http://localhost:3000/patients') } }
HTML代码
<tr *ngFor="let item of dataArray "> <td>{{item.firstname}}</td> <td>{{item.lastname}}</td> <td>{{item.age}}</td> <td>{{item.phone}}</td> <!-- 原代码此处缺少闭合的 }},需修正 --> <td>{{item.email}}</td>
HTTP GET响应数据
{"patients":[{"_id":"6374db3de99156199a548845","firstname":"yassine","lastname":"azaiez","email":"yassine@yahoo.fr","age":23,"phone":92810192,"__v":0},{"_id":"6375045dd2eeac54c6ecb89b","firstname":"malik","lastname":"karim","email":"malik@yahoo.com","age":12,"phone":999999,"__v":0},{"_id":"637607be05816c5a7829130d","firstname":"alex","lastname":"karima","email":"malik@yahoo.com","age":12,"phone":999999,"__v":0},{"_id":"637607d105816c5a7829130f","firstname":"alex","lastname":"karima","email":"malik@yahoo.com","age":12,"phone":999999,"__v":0},{"_id":"63768732bc19c7bb581a24af","firstname":"malik","lastname":"azaiez","email":"zk@hotmail.com","age":18,"phone":97829101,"__v":0}],"user":null}
解决步骤
1. 修正数据赋值逻辑
NgFor仅支持遍历数组类型,当前代码将整个响应对象(包含patients数组和user字段)赋值给dataArray,导致无法遍历。需修改组件中的订阅代码,提取响应里的patients数组:
this.ds.getAllPatients().subscribe(data=>this.dataArray=data.patients);
2. 修复HTML语法错误
原HTML代码中{{item.phone缺少闭合的}},需补充完整,避免渲染报错:
<td>{{item.phone}}</td>
3. 可选:类型优化(增强代码健壮性)
给dataArray指定明确类型并初始化为空数组,避免组件初始化时dataArray为undefined可能引发的问题:
// 定义患者类型 interface Patient { _id: string; firstname: string; lastname: string; email: string; age: number; phone: number; __v: number; } // 初始化空数组 dataArray: Patient[] = [];
内容的提问来源于stack exchange,提问作者Malik Azaiez
相关产品推荐
相关产品推荐

