如何使用返回http承诺的angular 2服务



我在这里遇到角度 2 的问题。我使用返回承诺的服务,但是当我尝试检索响应时,我遇到了错误。

我读了这个问题这是我的代码。

这是酒店服务网

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

这家酒店(组件)

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()然后回调:

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

dfsq的答案是正确的,但为了完整起见,以下是根据官方 Angular.io 建议的示例:

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

主要区别:

  • 处理then中的空响应;
  • 在进一步抛出错误之前,请先解决错误。

最新更新