gpt4 book ai didi

javascript - 如何使用返回http promise的angular 2服务

转载 作者:太空狗 更新时间:2023-10-29 17:36:02 25 4
gpt4 key购买 nike

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

我读了这个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();
}
}

我不知道。

最佳答案

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

关于javascript - 如何使用返回http promise的angular 2服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41810298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com