简体   繁体   English

Angular2 ng用于迭代JSON

[英]Angular2 ngFor Iterating over JSON

I´m fairly new to Angular2, and i want to read out a json file. 我是Angular2的新手,我想读出一个json文件。 It´s working, that I get the file from a REST-Client, i can save the file in a local variable in a component and furthermore I´m able to read properties of the variable. 它工作,我从REST客户端获取文件,我可以将文件保存在组件的本地变量中,此外我能够读取变量的属性。 Now I´m trying to read other properties (Array) with ngFor, but this isn´t working. 现在我试图用ngFor读取其他属性(Array),但这不起作用。 Here´s the html: 这是html:

//Working
<td>{{status.rights}}</td>
//Not working
<tr *ngFor="let folder of status.recfolders">
                                <td>{{folder.text}}</td>
                                <td>{{folder.size}}</td>
                                <td>{{folder.free}}</td>
                            </tr>

And the JSON: 和JSON:

{
  "status": {
    "rights": "full",
    "recfiles": "13",
    "recfolders": {
      "folder": [
        {
          "size": "7866296029184",
          "free": "3724003368960",
          "text": "\\\\edited\\Daten\\Videos\\Aufnahmen"
        },
        {
          "size": "59495149568",
          "free": "38696935424",
          "text": "C:\\Users\\edited\\Desktop"
        }
      ]
    }
  }
}

If i try it that way, Angular says Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." 如果我这样尝试,Angular说Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." If i try *ngFor="let folder of status.recfolders.folder" it´s not working either, but the error is self.context.status.recfolders is undefined... I hope someone can say me, what I´m doing wrong ;) Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."如果我尝试*ngFor="let folder of status.recfolders.folder"它也不起作用,但错误是self.context.status.recfolders未定义...我希望有人可以说我,我做错了什么;)

As folder contains array it should be there with *ngFor . 由于文件夹包含数组,因此应该使用*ngFor ?. operator will do the binding when folder array is available for the binding. 当文件夹数组可用于绑定时,operator将执行绑定。

NOTE : ?. 注意?. operator should be used when you are working with async call . 使用异步调用时应使用运算符。 For static data it is not required. 对于静态数据 ,不需要。

It should be, 它应该是,

*ngFor="let folder of status.recfolders?.folder"

You should use Elvis operator (?.) to avoid self.context error. 您应该使用Elvis operator (?.)来避免self.context错误。

Try this: 尝试这个:

<tr *ngFor="let folder of status.recfolders?.folder">
      <td>{{folder.text}}</td>
      <td>{{folder.size}}</td>
      <td>{{folder.free}}</td>
</tr>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM