簡體   English   中英

如何使用返回http promise的angular 2服務

[英]How to use angular 2 service which returns http promise

我在這里遇到角度2的問題。 我使用返回promise的服務但是當我嘗試檢索響應時出現錯誤。

這是我的代碼中的這個問題

這是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(組件)

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處理空響應;
  • 在把它扔得更遠之前把它弄錯了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM