我是角度2中的新手,并尝试迭代JSON对象。 JSON响应是:
{
"number":3,
"message":"success",
"people":[
{
"name":"Peggy Whitson",
"craft":"ISS"
},
{
"name":"Fyodor Yurchikhin",
"craft":"ISS"
},
{
"name":"Jack Fischer",
"craft":"ISS"
}
]
}
我的服务代码/ http获取请求:
@Injectable()
export class AstronautsHttpService{
constructor(private _http: Http) {}
getAstronauts(){
// return this._http.get('http://date.jsontest.com/')
return this._http.get('http://api.open-notify.org/astros.json')
.map((res:Response) => res.json());
}
}
显示组件是:
export class DisplayComponent{
private number:any;
private message:any;
private people:any
constructor(private AstronautService:AstronautsHttpService) {}
ngOnInit(){
this.number = this.AstronautService.getAstronauts()
.subscribe( Q => this.number = Q.number);
this.number = this.AstronautService.getAstronauts()
.subscribe( Q => this.message= Q.message);
this.message = this.AstronautService.getAstronauts()
.subscribe( data => {
this.people = data.people;
this.people.forEach(m => console.log(m.name))
this.people.forEach(m => console.log(m.craft));
});
}
}
我已经设法打印了号码和消息但是当涉及到迭代人员时它无法正常工作。
我真的很感激任何建议/帮助。
答案 0 :(得分:1)
你为什么要做三个服务调用得到单个Json。
你可以这样试试。
private people:any[]
ngOnInit(){
this.message = this.AstronautService.getAstronauts()
.subscribe( data => {
this.number = data.number;
this.message= data.message;
this.people = data.people;
this.people.forEach(m => {
console.log(m.name,m.craft);})
});
}
答案 1 :(得分:0)
尝试使用map方法迭代。,像这样:
.subscribe(
(data) => {
this.people = data.people;
this.people.map((person) => {
console.log(person.name, person.craft);
})
});