Angular 2-遍历json对象内的json数组 [英] Angular 2 - iterating over json array inside a json object

查看:250
本文介绍了Angular 2-遍历json对象内的json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Angular 2,并且一直在使用静态数组,现在我正在尝试学习有关读取远程数据的更多信息.

I'm learning Angular 2 and I've been working with static arrays, and now I'm trying to learn more about reading remote data.

我的app.component.ts:

import {Component} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';

@Component({
  selector: 'my-app',
  template:`
  <h1>Angular2 HTTP Demo App</h1>
  <h2>Foods</h2>
  <ul>
    <li *ngFor="#doc of docs">{{doc.id}}</li>
  </ul>
  `
})
export class AppComponent {

  public foods;
  public books;
  public movies;

  constructor(private http: Http) { }

  ngOnInit() {
    this.getFoods();
  }

  getFoods() {
    this.http.get('http://my API URL')
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.foods = data},
        err => console.error(err),
        () => console.log('done')
      );
  }

}

这是我的API网址显示结果的方式:

This is how my API url show the results:

  1. 一个名为"docs"的json对象.
  2. 具有ID和其他字符串的项的json数组.

我的目标是循环每个数组项并显示其中的数据(id,placeID等.)

My goal is to loop each array item and show the data inside it (id, placeID, etc..)

这是我的应用程序,完全不进行迭代:

This is my app, which makes no iteration at all:

我如何循环使用*ngFor每个json数组项?

How I can loop with the *ngFor each of ths json array items?

推荐答案

柱塞

要遍历数组:

<li *ngFor="let doc of docs">{{doc.id}}</li>


要遍历对象属性:

您将必须生成对象属性的Array

You will have to generate an Array of the object properties

generateArray(obj){
   return Object.keys(obj).map((key)=>{ return obj[key]});
}

并像使用它

<li *ngFor="let doc of docs">
   <span *ngFor="let v of generateArray(doc)"> {{v}} </span>
</li>

或者您可以用作管道.

这篇关于Angular 2-遍历json对象内的json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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