如何使用 *ngFor 显示 json 对象 [英] How to display json object using *ngFor
问题描述
我想显示来自 Firebase 的以下数据
I want to display the below data from Firebase
{
"-KBN9O_qqz-nZ9tPWFdM":{
"createdAt":1456399292790,
"isActive":true,
"name":"Hero 1"
},
"-KBN9gjJw1ZlMgt9pVsl":{
"createdAt":1456399371220,
"isActive":true,
"name":"Hero 2"
},
"-KBN9hYI4vYAsyh5k1lX":{
"createdAt":1456399374548,
"isActive":true,
"name":"Hero 3"
}
}
例如在做angular.io英雄之旅教程时
<li *ngFor="#hero of heroes">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
所以英雄id应该显示例如-KBN9hYI4vYAsyh5k1lX
和英雄名称应该显示例如 hero 3
So hero id should show for example -KBN9hYI4vYAsyh5k1lX
and hero name should show for example hero 3
我做了一些研究,发现 @Thierry Templier 的这个 stackoverflow 解决方案 使用 *ngFor 访问对象的键和值
I have done some research and come across this stackoverflow solution by @Thierry Templier access key and value of object using *ngFor
(1) 这是我的问题的正确解决方案吗?
(1) Is this the right solution to my problem?
(2) 这个问题有没有更简单的解决方法,因为我觉得开发者用Angular2显示这样的json数据真的很普遍.
(2) Is there a simpler solution to this problem because I feel that it would be really common for developers using Angular2 to display such json data.
推荐答案
您需要实现自定义管道来执行此操作.ngFor
只支持数组,不支持对象.
You need to implement a custom pipe to do this. ngFor
only supports array and not object.
这个管道看起来像这样:
This pipe will look like that:
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}
并像这样使用它:
<span *ngFor="#entry of content | keys">
Key: {{entry.key}}, value: {{entry.value}}
</span>
查看此问题了解更多详情:
See this question for more details:
这篇关于如何使用 *ngFor 显示 json 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!