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();
}
})
希望這會有所幫助!祝你今天過得愉快。
添加回答
舉報