5

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.

user3483203
  • 50,081
  • 9
  • 65
  • 94
Cecep
  • 87
  • 3
  • 10

2 Answers2

3

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);
}
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • thats really work for me. but why i must return it. i mean it return inside return? i see in the documentation it use `response.json().data as hero[]` – Cecep Jan 23 '17 at 15:58
  • Because whatever you return from then callback is passed into next callback in chain. Since you didn't return it yourself, implicit `undefined` is returned for you. – dfsq Jan 23 '17 at 16:00
  • You can return `response.json().data` but you need to return something if you plan to access it in promise chain. – dfsq Jan 23 '17 at 16:00
  • Thanks. that really explain me about promise. :) – Cecep Jan 23 '17 at 16:06
1

The dfsq's answer is correct, but for the completeness' sake, below is an example according to the official Angular.io recommendations:

load(): Promise<any> {
    return this.http.get(this.BASEURL + 'api/client/hotel/load')
        .toPromise()
        .then(response: Response) => response.json() || {})
        .catch((error: Response | any) =>
        {
            let errMsg: string;
            if (error instanceof Response) 
            {
                const body = error.json() || '';
                const err = body.error || JSON.stringify(body);
                errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
            }
            else
                errMsg = error.message ? error.message : error.toString();

            return Promise.reject(errMsg);
        });
}

Key differences:

  • handle empty response in the then;
  • pretty up the error before throwing it further.
Alex Klaus
  • 8,168
  • 8
  • 71
  • 87
  • yeah. i think i need this instead of returning just an err obj. thanks alex. i think its more joy now. if u have more tricky stuff about angular, let me see!! :) – Cecep Jul 05 '17 at 06:15