以角度 2 在 Ngfor 上迭代一个 json 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37431578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iteration a json object on Ngfor in angular 2
提问by Anna
I'm having trouble iteration a json object in the Ngfor, there is my template :
我在 Ngfor 中迭代 json 对象时遇到问题,有我的模板:
template:
模板:
<h1>Hey</h1>
<div>{{ people| json}}</div>
<h1>***************************</h1>
<ul>
<li *ngFor="#person of people">
{{
person.label
}}
</li>
</ul>
people is the json object that I'm trying to iterate, I'm having rhe result of (people | json) and not getting the list, here is a screenshot:
people 是我试图迭代的 json 对象,我得到了 (people | json) 的结果,但没有得到列表,这是一个截图:


and to finish, here is a part of json file :
最后,这是 json 文件的一部分:
{
"actionList": {
"count": 35,
"list": [
{
"Action": {
"label": "A1",
"HTTPMethod": "POST",
"actionType": "indexation",
"status": "active",
"description": "Ajout d'une transcription dans le lac de données",
"resourcePattern": "transcriptions/",
"parameters": [
{
"Parameter": {
"label": "",
"description": "Flux JSON à indexer",
"identifier": "2",
"parameterType": "body",
"dataType": "json",
"requestType": "Action",
"processParameter": {
"label": "",
"description": "Flux JSON à indexer",
"identifier": "4",
"parameterType": "body",
"dataType": "json",
"requestType": "Process"
}
}
},
please feel free to help me
请随时帮助我
回答by Thierry Templier
Your peopleobject isn't an array so you can iterate over it out of the box.
您的people对象不是数组,因此您可以开箱即用地对其进行迭代。
There is two options:
有两种选择:
You want to iterate over a sub property. For example:
<ul> <li *ngFor="#person of people?.actionList?.list"> {{ person.label }} </li> </ul>You want to iterate over the keys of your object. In this case, you need to implement a custom pipe:
@Pipe({name: 'keys'}) export class KeysPipe implements PipeTransform { transform(value, args:string[]) : any { if (!value) { return value; } let keys = []; for (let key in value) { keys.push({key: key, value: value[key]}); } return keys; } }and use it this way:
<ul> <li *ngFor="#person of people | keys"> {{ person.value.xx }} </li> </ul>See this answer for more details:
您想要迭代子属性。例如:
<ul> <li *ngFor="#person of people?.actionList?.list"> {{ person.label }} </li> </ul>您想遍历对象的键。在这种情况下,您需要实现一个自定义管道:
@Pipe({name: 'keys'}) export class KeysPipe implements PipeTransform { transform(value, args:string[]) : any { if (!value) { return value; } let keys = []; for (let key in value) { keys.push({key: key, value: value[key]}); } return keys; } }并以这种方式使用它:
<ul> <li *ngFor="#person of people | keys"> {{ person.value.xx }} </li> </ul>有关更多详细信息,请参阅此答案:

