2 回答
TA贡献1880条经验 获得超4个赞
好吧,你应该把你的Promisefrom还给你getDistricts。此外,您过度设计并使async/await概念复杂化。我知道你不想使用Observables,但我还是建议你使用它们。
有了 promises,async/await你就会明白如何使用它们:
async getDistricts(): Promise<District[]> {
const { results } = await this.districtDataService.getDistrictData();
return results;
}
async ngOnInit(): Promise<void> {
this.districts = await this.getDistricts();
for (const district of this.districts){
console.log(district);
}
}
它Observable看起来像这样:
getDistricts(): Observable<District[]> {
return this.districtDataService.getDistrictData().pipe(
map(({ results }) => results as District[])
);
}
ngOnInit(): void {
this.getDistricts().subscribe((districts) => {
this.districts = districts;
for (const district of this.districts){
console.log(district);
}
});
}
TA贡献1820条经验 获得超10个赞
只是为了提供任何需要按所需顺序进行多个 http 调用的人。正如其他人所提到的,我将异步等待的概念过于复杂化了。诀窍是使用可观察对象,使用 .toPromise() 将它们转换为 Promises,使用 .then() 将数据放入我的变量中,然后使用 .finally(async () => { ... }).
这是我的最终代码:
async ngOnInit(): Promise<void> {
await this.districtDataService.getDistrictData().toPromise().then(response => {
this.districts = response.results as District[];
console.log(this.districts);
}).finally(async () => {
for (const district of this.districts){
await this.districtDataService.getBuildingsOfDistrict(district.id).toPromise().then(response => {
this.buildings = response.results as Building[];
console.log(this.buildings);
}).finally(async ()=> {
for(const building of this.buildings){
await this.districtDataService.getDoorsOfBuilding(building.id).toPromise().then(response => {
this.doors = response.results as Door[];
console.log(this.doors);
}).finally(async () => {
for(const door of this.doors){
await this.doorNodes.push(new districtNodeImpl(false,null,null,door,null));
}
})
await this.buildingNodes.push(new districtNodeImpl(false,null,building,null,this.doorNodes));
}
})
await this.dataSource.push(new districtNodeImpl(false,district,null,null,this.buildingNodes));
console.log(this.dataSource);
this.buildingNodes = new Array();
this.doorNodes = new Array();
}
})
希望这会有所帮助!祝你今天过得愉快。
添加回答
举报