簡體   English   中英

如何讓 angular 12 組件等待服務返回 api 調用

[英]How to have angular 12 component wait for service to return api call

I am building a function that makes an API call after inputs are provided by the user on the HTML via dropdowns, once selected they trigger an API call on my service via the component, but my component is not waiting for the service to return before executing我的 function 的 rest

從 service.ts 調用 API:

      this.fullSnapData =  await new Promise((resolve,reject) =>{
        this.apiService.GetSnapshotData(SnapShotData)
        .subscribe((data) =>{
          console.log(data);
          const fullSnapData = data
          console.log("fetched from db ", fullSnapData)
          this.fullSnapData= fullSnapData
          resolve(data)
        })
      })
      console.log("fullSnapData ", this.fullSnapData)
      return this.fullSnapData

Component.ts 調用服務剛剛完成:

let graphServiceData = this.service.getGraphServiceData(selectedBranch, timeVariable, timeScopes)

我假設我在 component.ts 中遺漏了一些東西,實際上讓它等待 controller 上的 promise 結束

您需要學習如何將 observables 鏈接在一起。 這是一篇很好的文章/示例,最后附有鏈接供您閱讀:

https://angularlovefest.com/index.php/2022/08/02/avoiding-nested-subscriptions-in-angular/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM