Display data from http service : ionic2


#1

I try to get data from service but fail to display it in home page, please advice to solve it,
i use chrome to debug, it show that data result .
here what i try so far :slight_smile:

mypos.service.ts

import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import {Categories} from './menu';

@Injectable()

export class MyposService{  

private sambaUrl = 'http://localhost:9000/api/graphql';
private headers = new Headers({'Content-Type':'application/json'}) ;
private getCategoriesScript(){
    return `{categories: getMenuCategories(menu:"Menu"){id,name}}`;
} 
     constructor(public http: Http) {
     //console.log(' data menu provider');
   }

loadmenu():Promise<Categories[]>{
    const query = this.getCategoriesScript();     
    return this.http         
      .post(this.sambaUrl,JSON.stringify({query:query}),{headers: this.headers})
      .toPromise()
      .then(response => response.json().categories as Categories[])
      .catch(this.handleError);
}

private handleError(error : any):Promise<any>{
    console.error('Terjadi kesalahan', error);
    return Promise.reject(error.message || error);
}

}

home.ts

import { Component, OnInit } from '@angular/core';
import { NavController } from 'ionic-angular';
import {Categories} from '../../app/menu';
import {MyposService} from '../../app/mypos.service';

@Component({
 
  selector: 'page-home',
  templateUrl: 'home.html',
  providers:[MyposService]
})
export class HomePage implements OnInit {

  listmenu : Categories[];

  constructor(public navCtrl: NavController,
               private myposService : MyposService,
                ) { }
  ngOnInit():void{
   this.loadmyMenu(); 
  }
 
  loadmyMenu(){
   return this.myposService.loadmenu()
  .then(listmenu => this.listmenu = listmenu);
  }
      
}

home.html

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Welcome TO myPOS Client Android!</h2>

 <ion-list>
   <ion-item *ngFor="let mm of listmenu">
    <span>{{mm.id}}</span>, <span>{{mm.name}}</span>
  </ion-item>
 </ion-list>
</ion-content>

menu.ts

export class Categories {
    id: string;
    name : string;
}

the result in chrome


#2

Initialize this early, so even if the template tries to access it before the result has come back from the server, it should just look like an empty list.


#3

i already try that, but listmenu still empty.