Http.get not passing data to page class variables


#1

Hi, i am able to get data from REST api but in html it show me undefined, i have followed this tutorial to get data

its work fine Ionic Framework : ionic-angular 3.2.1 but with Ionic Framework : ionic-angular 3.3.0 undefined data.

here is my provider method

getHomeData(){

 if (this.data) {
    return Promise.resolve(this.data);
  }

  	return new Promise(resolve => {
	    this.http.get(SERVER_NAME+'home')
	      .map(res => res.json())
	      .subscribe(data => {
	      	this.data = data;
	        resolve(this.data);
	      });
	  });
  }

method in my page typescript

homeData: any;
this.homeService.getHomeData().then(data => {
      this.homeData = data;
      console.log(this.homeData); // work fine till here but in html its undefined 
    });

homeData in html is undefined it drive me crazy, i don’t understand where is the problem.


#2

any who can help ? i am stuck with this problem.


#3

You must initialize homeData to something so that the template can render properly even before getHomeData()'s return resolves. You should also declare a proper interface type for homeData instead of abusing any, and here is how I would write the provider. The way you have it is needlessly instantiating Promises and does not propagate errors properly.

export class HomeService {
  homeData: Promise<HomeData>;
  constructor(http: Http) {
    this.homeData = http.get(SERVER_NAME+'home')
      .map(rsp => rsp.json())
      .toPromise();
  }
}