【问题标题】:angular2 NgFor only supports binding to Iterables such as Arraysangular2 NgFor 仅支持绑定到 Iterables,例如 Arrays
【发布时间】:2016-09-15 20:13:24
【问题描述】:

Angular2 rc.6

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

core.umd.js:5995 例外:app/modules/mbs/components/menu.html:5:4 中的错误由以下原因引起:找不到“object”类型的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Arrays 等 Iterables。

我的 html 循环,注意:我只是想在响应中迭代属性和数组。

<li *ngFor="let item of menuItems">
{{item}}
</li>

我的服务方式

getMenuItems():Promise<any>{
    return this.http.get('api/menu').toPromise().
    then(response => response.json())
        .catch(this.handleError)

}

以下是我的 json 响应

{  
"text":"Menu",
   "children":[
      {
         "text":"Home",
         "url":"/spatt-web/home"
      },
      {
         "text":"Configure",
         "children":[
            {
               "text":"Tri-Party Program",
               "children":[
                  {
                     "text":"Margins and Filters",
                     "url":"/sp-rrp/config/operation"
                  },
                  {
                     "text":"Fields and Desirability",
                     "url":"/spatt-rrp/config/program"
                  }
               ]
            },
            {
               "text":"Shared Settings",
               "url":"/shared-config/config"
            },
            {
               "text":"SOMA Limits",
               "url":"/outright-config/config"
            }
         ]
      },
      {
         "text":"Plan",
         "children":[
            {
               "text":"Tri-Party RRP Operations",
               "url":"/spatt-rrp/plan"
            }
         ]
      },
      {
         "text":"Track"
      },
      {
         "text":"Administer"
      },
      {
         "text":"Help",
         "children":[
            {
               "text":"RRP Operations",
               "url":"RRPference"
            },
            {
               "text":"RRP Margin Calls and Recalls",
               "url":"RRPRecallference"
            }
         ]
      }
   ]
}

【问题讨论】:

  • 你期望的结果是什么?
  • 你想展示什么?正如错误所示,您不能简单地使用 NgFor 循环访问对象中的成员。有办法解决它,但我需要先了解您要做什么
  • 感谢您的评论。我只是想显示属性并遍历子数组

标签: angular angular2-services


【解决方案1】:

看起来像你想要的

<li *ngFor="let item of menuItems.children">
{{item}}
</li>

【讨论】:

  • 非常感谢,这有助于我在使用 deezer api 时使用我的 angular 5 应用程序。
【解决方案2】:

如果你试图迭代一个对象:

  <div *ngFor="let location of locations | keyvalue">
       {{location.key}} - {{location.value | json}}
  </div>

KeyValuePipe Documntation

【讨论】:

  • 这帮助我遍历了模板驱动的表单验证错误。
  • 这个keyvalue真的很不错...生活和学习! :D
【解决方案3】:

一般来说,错误意味着您试图迭代一个对象而不是数组或可观察对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-01
    • 2017-09-07
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多