【问题标题】:ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables错误错误:找不到类型为“对象”的不同支持对象“[对象对象]”。 NgFor 只支持绑定到 Iterables
【发布时间】:2018-10-12 02:35:36
【问题描述】:
onGetForm() {
  this.serverData.getData('questionnaire/Student Course Review')
    .subscribe(
       (response: Response) => {
          this.questionnaire = response.json();
          let key = Object.keys(this.questionnaire);
          for (let i = 0; i < key.length; i++) {
            this.currentQuestionsValue.push(this.questionnaire[key[i]])
          }
        },
        (error) => console.log('Form Error', error)
      )
  }

我的 html 循环,注意:我只是想迭代

<form>
  <div *ngFor="let data of currentQuestionsValue">
    <div *ngFor="let d of data.items ">
      <strong> {{ d.sno }}). </strong>
      <span>{{ d.question}}</span>
      <div *ngFor="let op of d.options">
        <label>
          <input type="radio" name="option">
          <span>{{ op }}</span>
        </label>
      </div>
    </div>
  </div>
</form>

在 json 数据上运行循环时出现以下错误。

错误错误:找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Arrays 等 Iterables。

我想展示这些物品。

【问题讨论】:

  • 因为您试图显示 options 这是对象,因此您收到此错误。

标签: angular typescript firebase firebase-realtime-database


【解决方案1】:

这里 options 不是 array ,它只是简单的 json object ,因为下面的行你会得到错误:

<div *ngFor="let op of d.options">

解决方案:

组件端:

objectKeys = Object.keys;

模板方面:

<div *ngFor="let key of objectKeys(d.options)">
    <label>
        <input type="radio" name="option">
        <span>{{ d.options[key] }}</span>
    </label>
</div>

供参考:WORKING DEMO

【讨论】:

    【解决方案2】:

    这是因为你的第二个 ngFor 循环试图循环一个对象。

    选项值是一个具有属性'option1','option2'...的对象;

    所以你必须像你一样把它改成数组。

    this.questionnaire = response.json();
          let key = Object.keys(this.questionnaire);
          for (let i = 0; i < key.length; i++) {
            this.currentQuestionsValue.push(this.questionnaire[key[i]])
          }
    for( let j = 0; j < this.currentQuestionsValue.length ; j++) {
          this.currentQuestionsValue[j].options =  Object.keys(this.currentQuestionsValue[j].options).map(i => options[i])
       }
    

    【讨论】:

      猜你喜欢
      • 2020-11-22
      • 1970-01-01
      • 2022-11-18
      • 2022-11-19
      • 1970-01-01
      • 2018-12-31
      • 2021-03-17
      • 2023-01-26
      • 2020-08-29
      相关资源
      最近更新 更多