我有一个 Trip 对象:
{ "id": "1", "country":"UK", "city": "London" }
我正在尝试创建一个编辑表单,在该表单中填充来自 trip 对象的值。我能够填充国家/地区下拉列表(在 ngOnInit()
中),并且所选国家/地区绑定(bind)到 trip.country
。但是我无法获取那个国家/地区的城市,因为显然 trip
在应该获取 trip.country
时仍然是 undefined
> 找到那个国家的城市。 (我尝试打印行程,结果未定义)
我尝试将异步与 getTrip()
函数一起使用,但我得到的错误是:
Error:(71, 21) TS1055:Type 'void' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.
我认为解决方案是某种异步/等待/ promise 策略,但我无法掌握它。
export class TripEditorComponent implements OnInit {
trip;
countries;
cities;
ngOnInit() {
this.getTrip();
this.countries = this.countryService.getCountries().subscribe(
data => { this.countries = data;},
err => console.error(err),
() => console.log('done loading countries')
);
console.log("this trip: ", this.trip) //this is undefined
this.cities = this.cityService.getCitiesByCountry(this.trip.country).subscribe(
data => { this.cities = data; },
err => console.error(err),
() => console.log('done loading cities') );
}
getTrip(): void {
const id = this.route.snapshot.paramMap.get('id');
if (id) {
this.tripService.getTrip(id).subscribe(trip => { this.trip = trip; });
} else {
this.trip = new Trip();
}
}
}
我们将不胜感激。
最佳答案
尝试这样的事情:
getTrip(): Promise{
return new Promise((resolve, reject) => {
const id = this.route.snapshot.paramMap.get('id');
if (id) {
this.tripService.getTrip(id).subscribe(
trip => {
this.trip = trip;
resolve();
},
error=>reject(error)
);
}
else {
this.trip = new Trip();
resolve();
}
})
}
用法:
this.getTrip().then(()=>{
/*your callback here*/
})
.catch(error=>{
/*catch exception here*/
})
如果你想使用 async/await,请确保你在 compilerOptions (tsconfig.json) 字段中的“target”具有“ES6”值
关于javascript - 如何在 Angular/Nodejs 中使用异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48090217/