0

I am hitting my API five times with different request data and pushing all response to an array and using .map to map the response array to my original array to set data but it is not working correctly my response data show it is undefined.

Mycode: Status is the request data I am hitting to API to get response and statusArray is the array I need to set the data from response.

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

For me the return this.temp return value but when i assign it to arr and print it in console it get undefined. Can I know how to do this?

R SUBASH
  • 41
  • 1
  • 1
  • 7
  • Careful, async await works with Promises, and what you are doing is to mix Promises and Observables. – JSON Derulo Jan 26 '21 at 14:52
  • Does this answer your question? [Is it a good practice using Observable with async/await?](https://stackoverflow.com/questions/49596641/is-it-a-good-practice-using-observable-with-async-await) – JSON Derulo Jan 26 '21 at 14:52

1 Answers1

0

I don't see the need for async/await here. It would serve better to restructure the array as an object and use Object.key() with RxJS forkJoin to trigger all the requests in parallel. It could then be piped in with RxJS map operator to transform the data.

Try the following

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();
}
ruth
  • 29,535
  • 4
  • 30
  • 57
  • When I try to print in console the status object it get only values 0. Instead of response value. When I try to expand the Object value It get correct response value. Can I know the reason for it – R SUBASH Jan 28 '21 at 05:08
  • `console.log` has a history of misleading object outputs. See here: https://stackoverflow.com/a/30150527/6513921. – ruth Jan 28 '21 at 08:14