我试图在HTTP请求之后返回一个promise但是当我在我的组件上打印返回时我得到了未定义。
服务:
getPlace() {
let promise = new Promise((resolve, reject) => {
this.http.get('http://localhost:3000/api/place/')
.toPromise()
.then(
res => { // Success
this.results = res.results.map(item => {
var place = new Place();
place.place_id = item.place_id;
place.name=item.name;
place.vicinity=item.vicinity;
place.coordinates = new Coordinates();
place.coordinates.latitude = item.geometry.location.lat;
place.coordinates.longitude = item.geometry.location.lng;
return place;
});
resolve();
console.log( this.results);
},
msg => { // Error
reject(msg);
}
);
});
return promise;
}
这是我的组件调用:
getPlace(): void{
this.cityService.getPlace().then( (res) => {console.log(res);
});
}
无论你传递给.then()
,resolve()
中的参数函数都将作为参数。
因此,当你做resolve('stuff')
然后最终.then(r => console.log(r))
将打印'stuff'
。
你正在获得undefined
,因为现在你的resolve
被调用而没有参数:
res => { // Success
this.results = res.results.map(item => {
var place = new Place();
place.place_id = item.place_id;
place.name=item.name;
place.vicinity=item.vicinity;
place.coordinates = new Coordinates();
place.coordinates.latitude = item.geometry.location.lat;
place.coordinates.longitude = item.geometry.location.lng;
return place;
});
resolve(); // <==== resolve without arguments here
console.log( this.results);
},
既然你想让.then()
获得results
,请将它添加到resolve
。上面的代码应该是:
res => { // Success
this.results = res.results.map(item => {
var place = new Place();
place.place_id = item.place_id;
place.name=item.name;
place.vicinity=item.vicinity;
place.coordinates = new Coordinates();
place.coordinates.latitude = item.geometry.location.lat;
place.coordinates.longitude = item.geometry.location.lng;
return place;
});
resolve(this.results); // <===== changed this line
console.log( this.results);
},
您将返回undefined,因为您没有使用Promise解析。
this.http.get('http://localhost:3000/api/place/')
.toPromise()
.then(
res => { // Success
this.results = res.results.map(item => {
var place = new Place();
place.place_id = item.place_id;
place.name=item.name;
place.vicinity=item.vicinity;
place.coordinates = new Coordinates();
place.coordinates.latitude = item.geometry.location.lat;
place.coordinates.longitude = item.geometry.location.lng;
//return place; Remove this
});
resolve(this.results);
console.log( this.results);
},
msg => { // Error
reject(msg);
}
);