我有角2这里的麻烦。 我使用返回承诺的服务,但是当我尝试回复响应时出现错误。如何使用角度分2次服,返回HTTP承诺
我在读这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();
}
}
我不知道。
这就是真正为我工作。但为什么我必须回报它。我的意思是它返回内部? 我在文档中看到它使用'response.json()。data as hero []' – Cecep
因为无论你从哪里返回,回调都会传递到下一个回调链中。既然你没有自己返回,隐式的'undefined'就会返回给你。 – dfsq
您可以返回'response.json()。data',但如果您打算在promise链中访问它,则需要返回一些内容。 – dfsq