Angular中NgFor遍历对象报错及遍历实现技术问询
解决Angular NgFor "Cannot find a differ supporting object '[object Object]'" 报错
这个报错的核心原因很明确:NgFor指令只能绑定到可迭代对象(比如数组、Map、Set),如果尝试遍历普通的JavaScript对象就会触发这个错误。结合你的代码来看,问题出在第二层的*ngFor="let d of data"——你推到currentQuestionsValue里的data本身还是一个非可迭代的对象,而非数组。
下面给你两种针对性的解决思路:
思路一:在模板中直接把对象转成可迭代数组
如果你的data是键值对形式的对象(比如{question1: '内容1', question2: '内容2'}),可以利用Object.entries()、Object.keys()或Object.values()把它转成数组后再遍历。
步骤:
- 在组件类中把
Object暴露给模板(因为Angular模板默认不能直接访问全局Object):
// 组件类中添加这一行 Object = Object;
- 修改模板中的第二层遍历:
<form> <div *ngFor="let data of currentQuestionsValue"> <!-- 如果你需要键和值 --> <div *ngFor="let [key, value] of Object.entries(data)"> 键:{{key}},值:{{value}} </div> <!-- 或者如果你只需要值 --> <!-- <div *ngFor="let value of Object.values(data)"> {{value}} </div> --> </div> </form>
思路二:在组件中提前处理数据(推荐)
如果你不想在模板里写太多逻辑,可以在获取数据时就把每个data转成可迭代数组,再推到currentQuestionsValue中:
修改你的onGetForm()方法:
onGetForm() { this.serverData.getData('questionnaire/Student Course Review') .subscribe( (response: Response) => { this.questionnaire = response.json(); // 确保currentQuestionsValue是初始化好的数组 this.currentQuestionsValue = []; const keys = Object.keys(this.questionnaire); for (let i = 0; i < keys.length; i++) { // 将对象转成键值对数组 const convertedData = Object.entries(this.questionnaire[keys[i]]); this.currentQuestionsValue.push(convertedData); } }, (error) => console.log('Form Error', error) ) }
然后模板就可以直接遍历转好的数组:
<form> <div *ngFor="let data of currentQuestionsValue"> <div *ngFor="let [key, value] of data"> 键:{{key}},值:{{value}} </div> </div> </form>
额外注意点
别忘了在组件类中提前初始化currentQuestionsValue为数组,避免初始状态下的undefined问题:
currentQuestionsValue: any[] = [];
内容的提问来源于stack exchange,提问作者Adeel
相关产品推荐
相关产品推荐

