如何使用显示JSON对象* ngFor [英] How to display json object using *ngFor

查看:280
本文介绍了如何使用显示JSON对象* ngFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从火力地堡显示以下数据

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
和主人公的名字应显示例如英雄3

我已经做了一些研究,并通过@Thierry TEMPLIER的访问键和使用对象的值* 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.

这将管看起来像:

@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:

  • access key and value of object using *ngFor

这篇关于如何使用显示JSON对象* ngFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆