0

Im trying to display below JSON object in an ionic2 application. I am getting a blank screen while running the application. i tried some tutorials but no progress.

 [
  {
    "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>
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Abhishek
  • 7
  • 6
  • That is not valid JSON though...? Did you just cut it down for demo purposes? Does your console output any error? – Patrick Apr 04 '17 at 13:52

2 Answers2

0

Move the service call outside of the constructor and place it inside ngOnInit

ngOnInit() {
 this.http.get('http://url.com/api').map(res => res.json()).subscribe(data => {
        this.progs = data;
    });
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

While it is better to do asynchronous calls in lifecycle hooks rather than the constructor as @Sajeetharan mentions in his answer, your issue is the view gets loaded before progs is set. Use an *ngIf to check for the value so that it gets loaded after the value is set.

<ion-list *ngIf="progs">

    <ion-item *ngFor="let prog of progs">
      {{prog.programName}}
    </ion-item>

  </ion-list>
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103