Angular 2 - 在 json 对象内迭代 json 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36162594/
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
Angular 2 - iterating over json array inside a json object
提问by TheUnreal
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.
我正在学习 Angular 2 并且我一直在使用静态数组,现在我正在尝试了解有关读取远程数据的更多信息。
My app.component.ts:
我的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')
);
}
}
This is how my API url show the results:
这是我的 API url 显示结果的方式:
- a json object named "docs".
- a json array of items with id's and other strings.
- 一个名为“docs”的 json 对象。
- 带有 id 和其他字符串的项目的 json 数组。
My goal is to loop each array item and show the data inside it (id, placeID, etc..)
我的目标是循环每个数组项并显示其中的数据(id、placeID 等)。
This is my app, which makes no iteration at all:
这是我的应用程序,它根本没有迭代:
How I can loop with the *ngForeach of ths json array items?
我如何循环使用*ngFor每个 json 数组项?
采纳答案by Ankit Singh
To loop over Array:
遍历数组:
<li *ngFor="let doc of docs">{{doc.id}}</li>
To loop over Object Properties:
要循环对象属性:
You will have to generate an Arrayof the object properties
您必须生成一个Array对象属性
generateArray(obj){
return Object.keys(obj).map((key)=>{ return obj[key]});
}
and use it like
并像使用它一样
<li *ngFor="let doc of docs">
<span *ngFor="let v of generateArray(doc)"> {{v}} </span>
</li>
Or you can use as Pipe.
或者您可以用作管道。


