【问题标题】:How to use angular 2 service which returns http promise如何使用返回http承诺的angular 2服务
【发布时间】:2017-06-08 04:42:08
【问题描述】:

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

我读到了这个this stact question 这是我的代码。

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

我不知道。

【问题讨论】:

    标签: javascript angular ionic2 undefined angular-promise


    【解决方案1】:

    你需要从 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);
    }
    

    【讨论】:

    • 这真的对我有用。但为什么我必须退回它。我的意思是它返回内部返回?我在它使用的文档中看到response.json().data as hero[]
    • 因为无论你从 then 回调返回什么,都会传递给链中的下一个回调。由于您没有自己返回,因此为您返回隐式undefined
    • 你可以返回response.json().data,但是如果你打算在promise链中访问它,你需要返回一些东西。
    • 谢谢。这真的向我解释了承诺。 :)
    【解决方案2】:

    dfsq的回答是正确的,但是为了完整起见,下面是根据官方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);
            });
    }
    

    主要区别:

    • 处理then中的空响应;
    • 在进一步抛出错误之前先完善错误。

    【讨论】:

    • 是的。我想我需要这个而不是只返回一个错误的 obj。谢谢亚历克斯。我认为它现在更快乐。如果你有更多关于角度的棘手问题,让我看看!! :)
    猜你喜欢
    • 2017-02-21
    • 2017-08-04
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 2016-10-25
    相关资源
    最近更新 更多