Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use angular 2 service which returns http promise

Tags:

I have a trouble with angular 2 here. I use service that return promise but when i try to retrive the response i got an error.

i was read this this stact question this my code.

this is HotelService.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

//rxjs promises cause angular http return observable natively.
import 'rxjs/add/operator/toPromise';

@Injectable()
export class HotelService {

    private BASEURL : any = 'http://localhost:8080/hotel/';

    constructor(private http: Http) {}  

    load(): Promise<any> {
        return this.http.get(this.BASEURL + 'api/client/hotel/load')
            .toPromise()
            .then(response => {
                response.json();
                //console.log(response.json());
            })
            .catch(err => err);
    }
}

this Hotel.ts (component)

import { Component, OnInit } from '@angular/core';
import { NavController } from 'ionic-angular';

import { HotelService } from '../../providers/hotel/hotelservice';

import { AboutPage } from '../../pages/about/about';
import { HotelDetailPage } from '../../pages/hoteldetail/hotel';

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

  public searchBoxActive = false;
  public hotels: any;

  constructor(
    private navCtrl: NavController,
    private hotelServ: HotelService
    ) { }

  load() {
    this.hotelServ.load()
      .then(res => {
        this.hotels = res;
        console.log(res); //why the rest is undefined?
        console.log('ini component');
      },
      err => err);
  }

  toggleSearchBox() {
    if (this.searchBoxActive == false) {
        this.searchBoxActive = true;
    } else {
        this.searchBoxActive = false;
    }
  }

  showAbout() {
    this.navCtrl.setRoot(AboutPage);
  }

  pushDetail(evt, id) {
    this.navCtrl.push(HotelDetailPage)
  }

  ngOnInit(): void {
    this.load();
  }
}

I have no idea.

like image 599
Cecep Avatar asked Jan 23 '17 15:01

Cecep


1 Answers

You need to return response.json() from promise then callback:

load(): Promise<any> {
    return this.http.get(this.BASEURL + 'api/client/hotel/load')
        .toPromise()
        .then(response => {
            return response.json();
        })
        .catch(err => err);
}
like image 183
dfsq Avatar answered Sep 21 '22 10:09

dfsq