打印从Angular2 JSON数组属性值 [英] print attributes values from JSON array in Angular2

查看:1642
本文介绍了打印从Angular2 JSON数组属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Angular2,我以这种方式取自火力地堡一些数据:

 数据集:任;
onGetData(){
    this._dataService.getAllData()
        。订阅(
        数据=> this.dataset = JSON.stringify(数据),
        错误=> console.error(错误)
    );

如果我打印我得到这个JSON:

<$p$p><$c$c>{\"-KE8XuCI7Vsm1jKDJIGK\":{\"content\":\"aaa\",\"title\":\"bbb\"},\"-KE8XvM268lWhXWKg6Rx\":{\"content\":\"cccc\",\"title\":\"dddd\"}}

我怎样才能打印出仅由标题的列表此JSON数组值?

我想有:BBB - DDDD


解决方案

您只能通过ngFor遍历数组。你的情况,你需要实现自定义管道来遍历一个对象的键。

类似的东西:

  @Pipe({名称:'键值'})
出口类KeysPipe实现PipeTransform {
  变换(值,ARGS:字符串[]):任何{
    让键= [];
    对(让值键){
      keys.push({键:键,值:值[关键]);
    }
    返回键;
  }
}

和使用这样的:

 &LT;跨度* ngFor =数据集#入门|键值&GT;
  标题:{{entry.value.title}}
&LT; / SPAN&GT;

有关详细信息,请参阅此问题:

I'm using Angular2 and I have retrieved some data from Firebase in this way:

dataset: any;
onGetData() {
    this._dataService.getAllData()
        .subscribe(
        data => this.dataset = JSON.stringify(data),
        error => console.error(error)
    );

if I print dataset I get this JSON:

{"-KE8XuCI7Vsm1jKDJIGK":{"content":"aaa","title":"bbb"},"-KE8XvM268lWhXWKg6Rx":{"content":"cccc","title":"dddd"}}

How can I print out a list made up of only the title values from this JSON array?

I'd like to have: bbb - dddd

解决方案

You can only iterate over an array using ngFor. In your case you need to implement a custom pipe to iterate over keys of an object.

Something like that:

@Pipe({name: 'keyValues'})
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;
  }
}

and use it like that:

<span *ngFor="#entry of dataset | keyValues">           
  Title: {{entry.value.title}}
</span>

See this question for more details:

这篇关于打印从Angular2 JSON数组属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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