【问题标题】:Use Async Await to Set Response Data in Typescript在 Typescript 中使用 Async Await 设置响应数据
【发布时间】:2021-04-30 08:44:13
【问题描述】:

我用不同的请求数据访问我的 API 五次并将所有响应推送到一个数组并使用 .map 将响应数组映射到我的原始数组以设置数据但它无法正常工作我的响应数据显示它未定义.

我的代码: Status 是我访问 API 以获取响应的请求数据,statusArray 是我需要从响应中设置数据的数组。

statusArray = [
{
status: "Submitted",
count: 0
},
{
status: "Approved",
count: 0
},
{
status: "Rejected",
count: 0
},
{
status: "Open",
count: 0
}

]; 
 arr;
 temp =[]; 
 status = ["Submitted", "Approved", "Rejected", "Open"];
 async sendToApi(){
    for(let val of this.status)
    {
     this.arr = await this.getdata(val);
    }
    console.log(this.arr);
     await this.resolveData(this.arr);
}
async getdata(status)
  {
    this._service.getStatusBasedCount(status).pipe(takeUntil(this._onDestroy))
    .subscribe(async res =>{
      if(res['err'] == 'N')
      {
       this.temp.push({status: res['dataType'], count: res['dataTypeValue']});
       return this.temp;
      }
      
    });
   
   
  }
  async resolveData(arr)
  {
    let data  = arr;
    console.log(data);
    this.statusArray=   this.statusArray.map((item, row) => {
      const found = data.find(
        element => item.status == element.status
      );
      return { ...item, ...found };
    });
    
  }

对我来说,返回 this.temp 返回值,但是当我将它分配给 arr 并在控制台中打印它时,它会变得未定义。我可以知道怎么做吗?

【问题讨论】:

标签: angular typescript async-await


【解决方案1】:

我认为这里不需要 async/await。将数组重组为对象并使用 Object.key() 和 RxJS forkJoin 来并行触发所有请求会更好。然后可以使用 RxJS map 运算符将其通过管道输入以转换数据。

试试下面的

status = {
  "Submitted": 0,
  "Approved": 0,
  "Rejected": 0,
  "Open": 0
}

getData() {
  forkJoin(
    Object.keys(this.status).map(status => 
      this._service.getStatusBasedCount(status).pipe(
        tap(res => {
          if (res['err'] == 'N') this.status[res['dataType']] = res['dataTypeValue']
        })
      )
    )
  ).subscribe();
}

【讨论】:

  • 当我尝试在控制台中打印状态对象时,它只得到值 0。而不是响应值。当我尝试扩展对象值时,它会得到正确的响应值。我能知道它的原因吗
  • console.log 有误导对象输出的历史。见这里:stackoverflow.com/a/30150527/6513921.
猜你喜欢
  • 2015-09-29
  • 1970-01-01
  • 2020-11-12
  • 2016-11-07
  • 2018-10-26
  • 2020-05-19
  • 2018-09-14
  • 2017-10-26
  • 1970-01-01
相关资源
最近更新 更多