Leverage Async Await for Setting Response Data in TypeScript

Currently, I am making multiple API requests with different data and storing all the responses in an array. Then, I am using .map to map the response array to my original array to update the data. However, it seems like the process is not working correctly as the response data is showing up as undefined.

In my code:


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

}

When returning this.temp value, it works fine. But when assigned to arr and printed in console, it returns undefined. Can anyone guide me on how to fix this?

Answer №1

In this scenario, async/await may not be necessary. It could be more beneficial to reformat the array into an object and utilize Object.key() in combination with RxJS forkJoin for concurrent request execution. This can then be followed by using the RxJS map operator for data transformation.

Consider implementing the following approach:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the power of Vue3 with reactive nested objects and the inclusion of

It seems like I've encountered a bit of a challenge... Perhaps a bug in Vue3 with Typescript and the composition API, or maybe I'm missing something. I'm facing an issue where I'm not getting any intellisense in my IDE (Webstorm) when ...

Troubleshooting: Issue with Angular 2 FormArray

Hey there! I'm currently working on my Angular 2 Recipe app where I want to display multiple ingredient details. I am using a FormArray but encountered an error while debugging with the browser developer tools. The error displayed on the Console tab i ...

The event fails to propagate up to the parent component

I have a project structure set up as follows: https://i.stack.imgur.com/bvmK5.jpg The todo-form component triggers the created event and I am looking to handle this event in the todos component. todo-form.component.html: <form class="todo-form" ( ...

The Express API controller is unexpectedly receiving empty strings

I am encountering an issue where my API is receiving an empty string instead of the expected data when I send post requests with a single string in the body. Below are the client, server, and controller components involved: Function call (client): const ...

Is it possible to synchronize the Lit cached DOM with the live DOM?

Utilizing the Lit framework for constructing my front-end UI components has been a game-changer. However, I have encountered an issue while incorporating our internal company design system's web components. One of these components has the ability to r ...

Utilizing sourcemaps in ionic for seamless linking

I've encountered an issue with source maps or a similar feature. After inserting console.log(...) in my code, the message appears in the console but links to the compiled JavaScript file instead of the original TypeScript file. Have I overlooked som ...

Best location for Angular PWA update handler?

Running a PWA app led me to think about decluttering the application.component. To achieve this, I created a dedicated service to monitor PWA updates and alert the user: import { Injectable } from '@angular/core'; import { MatSnackBar } from &qu ...

Ways to determine cleanliness or filthiness in an Angular 5 modal form?

I have a form within a modal and I only want to submit the form if there are any changes made to the form fields. Here is a snippet of my form: HTML <form [formGroup]="productForm" *ngIf="productForm" (ngSubmit)="submitUpdatedRecord(productForm.value) ...

Trigger an error in TypeScript with an embedded inner error

Is it possible to throw an Error with an inner Error in TypeScript, similar to how it's done in C#? In C#, you can achieve this by catching the exception and throwing a new one with the original exception as its inner exception: try { var a = 3; ...

Angular 2 (Final): Utilizing resetConfig for seamless integration of routes into lazy loaded modules

Trying to understand the process of dynamically adding routes from a lazy-loaded module. The core app has initial routes: export const routes = [{ path: "", component: HomeComponent }, { path: "moduleA", loadChildren: "app/moduleA/A.module ...

Creating a DynamoDB table and adding an item using CDK in Typescript

Can anyone guide me on how to add items to a Dynamodb Table using CDK and Typescript? I have figured out the partition/sort keys creation, but I am struggling to find a straightforward solution for adding items or attributes to those items. Additionally, ...

Seeking guidance for the Angular Alert Service

I'm relatively new to using Angular and I'm struggling to determine the correct placement for my AlertService and module imports. Currently, I have it imported in my core module, which is then imported in my app module. The AlertService functions ...

Struggling to grasp the concept of Observable Catch closure scope in Angular2?

Seeking guidance on using catch with Observables. I find myself confused and would appreciate some assistance. My goal is to handle a 403 error from the API by deleting the local token and marking the user as unauthenticated in my TokenStore. The approach ...

Creating a shared singleton instance in Typescript that can be accessed by multiple modules

Within my typescript application, there is a Database class set up as a singleton to ensure only one instance exists: export default class Database { private static instance: Database; //Actual class logic removed public static getInstance() ...

Angular - Dividing Values within Input Arrays

In the input field available to users, they can enter multiple inputs separated by commas. <div class="container"> Enter your values:<input type="text" multiple #inputCheck> <input type="submit"(cli ...

Testing the GET method in an Angular service: A guide

I'm currently facing an issue with my service method and unit test setup. Despite writing a unit test for the getter method, the coverage report indicates that this method is not covered. I would appreciate any advice on what might be going wrong in m ...

Angular is not programmed to automatically reflect updates made to my string array

let signalRServerEndPoint = 'https://localhost:44338'; this.connection = $.hubConnection(signalRServerEndPoint); this.proxy = this.connection.createHubProxy('MessagesHub'); this.proxy.on("ReceiveMessage", (message) => { ...

The never-ending scroll feature in Vue.js

For the component of cards in my project, I am trying to implement infinite scrolling with 3 cards per row. Upon reaching the end of the page, I intend to make an API call for the next page and display the subsequent set of cards. Below is my implementatio ...

Can type information be incorporated during compilation?

Consider the code snippet below: function addProperties(keys: String[]): Object { // For illustration purposes, this is a specific return return { firstProperty: "first_value", secondProperty: "second_value" }; } export defaul ...

Angular has surpassed the maximum call stack size, resulting in a Range Error

I am facing an issue while trying to include machine detail and a button bar in my app. Interestingly, this setup has worked perfectly fine in other parts of the application but is causing errors in the core module. Here is the error message main.ts impo ...