如何使用返回http承诺的angular 2服务 [英] How to use angular 2 service which returns http promise

查看:25
本文介绍了如何使用返回http承诺的angular 2服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的角度 2 有问题.我使用返回承诺的服务,但是当我尝试检索响应时出现错误.

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.

我读了这个这个stact问题这是我的代码.

i was read this this stact question this my code.

这是 HotelService.ts

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);
    }
}

这个Hotel.ts(组件)

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();
  }
}

我不知道.

推荐答案

你需要从promise返回response.json()然后回调:

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);
}

这篇关于如何使用返回http承诺的angular 2服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆