我试图在ionic2应用程序中显示JSON对象下面。我在运行应用程序时得到一个空白屏幕。我尝试了一些教程,但没有进展。
[
{
"program_id": 1000,
"programName": "Luna_Titan_L",
"costElement": "Material Cost",
"trackingID": "LT001S",
},
{
"program_id": 1001,
"programName": "Luna_Titan_L",
"costElement": "Material Cost",
"trackingID": "LR001S"
},
.....
]
home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
progs: any;
constructor(public navCtrl: NavController, public http: Http) {
this.http.get('http://url.com/api').map(res => res.json()).subscribe(data => {
this.progs = data;
});
}
}
home.html的
<ion-list>
<ion-item *ngFor="let prog of progs">
{{prog.programName}}
</ion-item>
</ion-list>
答案 0 :(得分:0)
将服务调用移到构造函数之外并将其放在ngOnInit
中ngOnInit() {
this.http.get('http://url.com/api').map(res => res.json()).subscribe(data => {
this.progs = data;
});
}
答案 1 :(得分:0)
虽然最好在生命周期钩子中进行异步调用而不是@Sajeetharan在他的回答中提到的构造函数,但问题是在设置progs
之前加载视图。使用*ngIf
检查值,以便在设置值后加载它。
<ion-list *ngIf="progs">
<ion-item *ngFor="let prog of progs">
{{prog.programName}}
</ion-item>
</ion-list>