What causes an empty array to appear outside of a FOR loop in Typescript (Angular CLI)?

After thorough research on similar issues, I couldn't find a solution to my problem. Hence, I am posting this question again to seek clarification on why this issue is occurring.

I have developed a web application where users can download data by clicking a button on one of the pages. Everything was running smoothly until I introduced a FOR loop to fetch additional data and append it to a new array. Below is the code snippet for better understanding:

employee-list.component.ts

import { Component, OnInit } from '@angular/core';
import { RestApiService } from "../shared/rest-api.service";

@Component({
  selector: 'app-employees-list',
  templateUrl: './employees-list.component.html',
  styleUrls: ['./employees-list.component.css']
})
export class EmployeesListComponent implements OnInit {

  // Code block omitted for brevity
  
}

In the download() method of this code, I am creating an array called reportData, which I later convert to CSV format for downloading purposes.

However, I noticed that this specific array reportData appears empty once we exit the

this.restApi.getEmployeeAsset(emp.id).subscribe
call within the parent for loop. This inconsistency baffles me, and I'm struggling to pinpoint the cause of this behavior.

To detect this issue, I logged results at two different points within the for loop - one before the API call's subscribe method (

console.log("Report Data is available here"+JSON.stringify(this.reportData))
) shows the populated reportData, while the other after the subscribe method (
console.log("Report data is empty here"+JSON.stringify(this.reportData))
) displays an empty array.

I would greatly appreciate any insights into what mistake I might be making and why this unexpected outcome is happening.

I encountered no errors and successfully downloaded the required file. However, it only contained the header column with no data. :(

Current workaround:

To address this issue temporarily, I moved the For loop logic from download() to loadEmployees(), which is then invoked under ngOnInit(). This ensures that necessary data is loaded when the component is initialized or executed (though I acknowledge this as not being the most efficient approach).

loadEmployees() {
    // Code block omitted for brevity
  }

While this solution works, it is not optimal since the reportData array is generated regardless of whether the Download button is clicked. Struggling with handling Promises or asynchronous coding, I adopted this method as a temporary fix.

Answer №1

Your code is experiencing an issue due to the combination of asynchronous and synchronous code, causing your data array not to be properly populated with results. The asynchronous code is still running when this.reportData.map() is being executed. It might be beneficial to explore utilizing rxjs operators in handling your API request.

download() {
  ...csv setup implemented here
  // Generating an array of observables based on the Employee array
  forkJoin(this.Employee.map(emp => this.restApi.getEmployeeAsset(emp.id))
    // Applying the map operator to manipulate data within the Observables
    .pipe(
      map(assets => {
        assets.forEach(
          if(assets.length !== 0){
            this.reportData.push(...defining the desired data)
          } else {
            this.reportData.push(...specifying the alternate data)
          }
      })
    ).subscribe(() => {
      ...perform necessary actions for mapping over this.reportData to generate your csv
    })
}

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

Using Typescript to Convert JSON Data into Object Instances

My challenge involves a Json object structure that looks something like this: { "key" : "false", "key2" : "1.00", "key3" : "value" } I am seeking to convert this in Typescript to achieve th ...

Angular-4: Exploring Component Reference on Click Event

One of my challenges involves dynamically adding different components when the user clicks, allowing them to add and remove any component. However, I am struggling to figure out how to reference the component where the user clicked in Angular-4. here are s ...

Transforming Boolean data types into text within an Angular 2 client-side application

Query I'm currently working on retrieving data from an API and displaying it in a table. One of the columns includes a status attribute that returns either true or false values. However, I would like to display "Active" or "Block" instead on the clie ...

How can you specify a tuple type in TypeScript for an array that is empty?

I'm attempting to convert a const object into a class in order to create readonly properties. The goal is to ensure that the values in these properties never change. Specifically, I'm trying to create a module property in my class that is define ...

Extract the content of a nested JSON object in ReactJS using map function

I am encountering an issue while attempting to map nested JSON data, specifically the error 'Element implicitly has an 'any' type'. The problem arises within the search component at: Object.keys(skills[keyName]).map() Below is the cod ...

How can I change a ReactNode into a text format?

I am looking for a way to convert the following code snippet into a string while preserving Tailwind CSS and other elements. My project uses Next.js with TypeScript and Tailwind CSS. Input : export default function Header_1() { return ( <div clas ...

Tips for effectively sending prop to a component in React with the help of TypeScript

Hey there, I'm working on a component called FormField which can accept either an icon for create or edit. Currently, I am using this FormField inside another component called SelectWithFormField. Here's how it looks: const FormField = ({create, ...

The TypeScript namespace does not exist or cannot be located

Currently, I am working on coding in TypeScript. The specific code pertains to an Angular 2 application, but the main focus of my inquiry lies within TypeScript itself. Within my project, there are certain files that contain various models, such as the exa ...

Ngrx optimized reducer with ahead-of-time compilation

I've been attempting to implement this reducer from the ReduxJs website using NgRx and Angular Cli: function createFilteredReducer(reducerFunction, reducerPredicate) { return (state, action) => { const isInitializationCall = state === ...

Utilizing React and MobX to dynamically render components based on observable arrays

I'm currently facing a challenge with trying to map an array in order to display components for each entry. Here's my current approach: Here is the structure of my RankStore; const RankStore = observable({ loading: false, error: "", ra ...

I seem to be stuck in an endless cycle with React hooks and I can't figure out the root cause

Explore the example here: https://codesandbox.io/s/wandering-wildflower-764w4 Essentially, my goal is to achieve the following: In the provided example, I have a server validation function that has been mocked. My objective is to maintain the state local ...

What is the best way to structure this React state container for modularity?

At my workplace, we have developed a state container hook for our React application and related packages. Before discussing what I'd like to achieve with this hook, let me provide some background information. Here is the functional code that's co ...

Simulated FileList for Angular 5 App Unit Testing

Imitation FileList In my pursuit of writing a unit test (Angular5), I have encountered the need for a FileList. Despite researching extensively, I have been unable to uncover any clues or solutions. I am starting to question whether this is even feasible ...

What is the best way to iterate over JSON data from an endpoint that contains multiple nested arrays using the .map() method?

Seeking to showcase weather API data from: () import Image from "next/image" interface Hour { time_epoch: number time: string temp_c: number temp_f: number is_day: number wind_mph: number wind_kph: number wind_deg ...

I am encountering a TypeScript error when using the createRef() method in React JS

Encountering some TypeScript warnings with the following dependencies: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8df9f4fde8feeeffe4fdf9cdbea3b8a3bf">[email protected]</a>, <a href="/cdn-cgi/l/email-protect ...

Supabase Type Generation Not Working as Expected

Every time I try to update my typing through the cli command, I keep getting this error message without much information for me to troubleshoot. 2023/03/01 09:34:01 Recv First Byte Error: failed to retrieve generated types: {"message":"Forbi ...

In Typescript, it is not permitted to assign a variable as a value within a styled array

Encountering a peculiar issue with TypeScript, Emotion.css, and React. The following code functions without any issues: import styled from '@emotion/styled-base'; const Layout = styled('div')([ { height: 48, color: ...

Ways to fix a "define is not defined" issue when utilizing jasmine karma with compiled typescript for component testing

I'm faced with an issue in my typescript app where the compiled code is stored in a single file named myjs.js within the js folder. Additionally, I have karma jasmine configured on my workspace. Inside myjs.js, there's a segment of code like thi ...

What is the best way to incorporate Tradingview's JavaScript into the render function of a React Typescript

I'm trying to incorporate some widgets into my Typescript React component. Here is the embed code export default class App extends React.Component { render(): ReactNode { return ( <div> Chart test <div className= ...

Encountering an ERROR during the compilation of ./src/polyfills.ts while running ng test - Angular 6. The module build

I encountered a problem in an angular project I am working on where the karma.config was missing. To resolve this, I manually added it and attempted to run the test using the command ng test. However, during the execution, an error message appeared: [./src ...