亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Angular 中異步 http 調用后數據消失

在 Angular 中異步 http 調用后數據消失

慕萊塢森 2022-12-22 12:00:46
我必須編寫一個顯示多個數據的樹組件,這對我來說可以很好地處理模擬數據。這里的問題是當我嘗試從服務器獲取數據時,讓我解釋一下:我有三個主要對象:區域、建筑物和門。正如您可能猜到的,doors 指的是 buildingId,而 buildingID 指的是地區。因此,要檢索數據并創建我的樹節點,我必須在非異步的 forEach 循環中執行一些 http 調用。我不會與您分享所有內容,只會分享一個最小化的問題,以便我可以輕松獲得幫助:此方法從服務器檢索區域數組并將其放入本地數組中:async getDistricts(){   this.districtDataService.getDistrictData().toPromise().then(async districts => {     this.districts = await districts.results as District[];   });}在我的 ngOnInit 上:ngOnInit() {this.getDistricts().then(async () => {  console.log(this.districts);  for (const district of this.districts){    console.log(district);  }})第一個 console.log(在 NgOnInit 中)返回一個空數組,這很令人驚訝,因為第一個方法將數據放在“this.districts”中。并在我將其放入后立即在第一種方法中記錄數據返回一個包含我的數據的數組。我想這與我使用的異步/等待有關。誰能幫忙?編輯 1:嘗試使用 this.getDistricts().finally() 而不是 this.getDistricts().then(),但沒有用。編輯 2:getDistrict 中的 console.log 在我的循環之前執行。預期的行為恰恰相反。已解決:在我的 HTTP 調用解決此問題后,將 for 循環放入 finally 塊中。所以正如答案所說,我認為我過度設計了異步/等待調用。基于此,我不得不重新思考我的工作。謝謝大家!
查看完整描述

2 回答

?
慕村225694

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);

    } 

  });

}


查看完整回答
反對 回復 2022-12-22
?
拉莫斯之舞

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();

   }

 })

希望這會有所幫助!祝你今天過得愉快。


查看完整回答
反對 回復 2022-12-22
  • 2 回答
  • 0 關注
  • 83 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號