Using a for loop in Angular's OnInit method to populate an array results in an array that

Firstly, within the ngOnInit function, I populate the items array:

id: string = '';
items: Item[] = [];

ngOnInit(): void {
    this.id = this.activatedRoute.snapshot.params['id'];
    this.itemService.getItems(this.id).subscribe({
      next: (res) => this.items = res
    })

After successfully retrieving the items array, I can then utilize *ngFor = "let item of items" to display a list of {{item.color}} on the HTML page. At this point, the items array is populated.

My next task is to extract each item's color and store it in a separate array. To accomplish this, I amend the ngOnInit method as follows:

let colorArray:string[] = [];
    for (let item of this.items) {
      colorArray.push(item.color)
    }

Additionally, within the same ngOnInit function, I add a console log statement:

console.log(colorArray);

However, upon execution, an empty array is logged to the console. What could have caused this issue?

Answer №1

There seems to be a timing issue here - the array is being populated before the data is actually available.

A better approach would be to refactor and map a new array once the results are returned, ensuring it is always filled at the right time.

id: string = '';
items: Item[] = [];
colorArray:string[] = [];

ngOnInit(): void {
    this.id = this.activatedRoute.snapshot.params['id'];
    this.itemService.getItems(this.id).subscribe({
      next: (res) => {
        this.items = res;
        this.colorArray = res.map(r => r.color);
      }
   })
}

Answer №2

setTimeout(()=>{
    const colors:string[] = [];
    for (const item of this.items) {
      colors.push(item.color);
    }
},1000)

This issue involves timing and the difference between queues and stacks. The second function is synchronous, meaning it returns a result before the first one which has to wait for a backend response to subscribe and then return a value. You can also utilize Angular lifecycle hooks by placing the second function inside ngAfterViewInit or ngDoCheck.

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 react-scripts leads TypeScript to mistakenly search for the incorrect file to import

Currently utilizing React and Relay in my project, I've encountered an issue with TypeScript. After relocating the directory where Relay generates some TypeScript files that are included in my app, TypeScript is unable to find them, presenting an unus ...

Adjust the selected value in real-time using TypeScript

Hey there, I've got a piece of code that needs some tweaking: <div> <div *ngIf="!showInfo"> <div> <br> <table style="border: 0px; display: table; margin-right: auto; margin-left: auto; width: 155%;"& ...

Ways to maintain data returned by forkJoin

I encountered a situation where I needed to retrieve results from 2 HTTP calls and combine them into an array that would be passed to a class instantiation. Below is the code snippet: export class VideoListComponent implements OnInit { @ViewChild(MatPag ...

Receiving intelligent suggestions for TypeScript interfaces declared within function parameters

Here is a simple example I put together: https://i.sstatic.net/Fdtfa.png In this example, intellisense provides suggestions for the interface of the object named test in the foo function. It works perfectly and I love it! However, if you declare that in ...

Node.js encounters a MODULE_NOT_FOUND problem

I am encountering an issue with MODULE_NOT_FOUND. I have tried various solutions from similar questions, but unfortunately, none of them have worked for me yet. Any assistance on this matter would be greatly appreciated. Thank you. My current task involve ...

Is Angular capable of determining which module to load for the frontend, or does it always need to load the entire application with all modules?

Is it possible for Angular 2 to selectively load specific modules for the frontend, or does it always have to load the entire application with all modules included? ...

Changing an array into an object in JavaScript without rearranging the keys

I have a collection { 1: {id: 1, first: 1, last: 5} 2: {id: 2, first: 6, last: 10} 3: {id: 3, first: 11, last: 15} } My goal is to reverse the order of items without rearranging the keys so that it looks like this: { 1: {id: 3, first: 11, last: 15} 2: { ...

Understanding the concept of a "class variable" in Typescript when referring to a variable that belongs to another class

When we declare a variable at the class level and assign it the type of another class, such as in the following code: let greeter: Greeter; //line 1 greeter = new Greeter("world"); What is contained within 'greeter' on line 1? ...

How to Dynamically Load SVGs in Angular 10 Without Using IMG or OBJECT Elements

I have been exploring a more streamlined method for loading SVG files without relying on IMG or OBJECT tags, as it limits my ability to control fill colors through external CSS. While using inline SVG seems like the best option, managing numerous component ...

Solving the issue of "Property does not exist on type 'never'" in a program involves identifying the root cause of

Issue An error message related to .cropper is occurring with the code snippet below. Error Message The property 'cropper' does not exist on type 'never'. Query How can I resolve the error associated with type 'never'? B ...

Is there a solution for the error message "Operator '+' cannot be used with types 'string | number' and 'string' | number'"?

Here's the scenario: I'm encountering an issue where I am invoking a function within another function. This inner function has the capability to return either a string or a number, and my goal is to combine that with another value. However, I kee ...

Angular Material design failing to display properly

Despite following the Angular Material guide on their website, I am still unable to see the gestures and design properly. I have meticulously followed all the steps outlined in the Angular Material guide. HTML <mat-radio-group> <mat-radio-but ...

How can I properly configure the 'main' file in angular-cli.json to utilize Express?

While attempting to set up an express server using Angular 2, I noticed in various configuration examples that the angular-cli.json file was being modified to point to a server.js file as the main configuration. However, after making this change, the appl ...

Disabling ESLint errors is not possible within a React environment

I encountered an eslint error while attempting to commit the branch 147:14 error Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions I'm struggling to identify the issue in the code, even ...

Leveraging the power of the moment.js package within an Ionic 2 project

I'm interested in implementing the Moment.js package for handling dates in my Ionic 2 project, but I'm unsure of how to proceed. You can find more information about Moment.js here. Currently, I have a datetime variable that I would like to local ...

When I utilize nuxt alongside TypeScript in conjunction with koa and execute the "dev" command, the terminal alerts me of compilation issues within Vue files that incorporate TypeScript syntax

nuxt: 2.6.2 node: 16.5.0 koa: 2.7.0 Here is the content of my package.json file : { ... "scripts": { "dev": "cross-env NODE_ENV=development nodemon server/index.ts --watch server --exec babel-node --presets @babel/ ...

Generic Abstract Classes in TypeScript

In my TypeScript code, I have an abstract generic class with a method that takes a parameter of a class type variable. When I tried to implement the abstract method in a derived class, I noticed that the TypeScript compiler doesn't check the type of t ...

Encountering a problem: array property length not found in Angular application?

I am trying to create a list of superheroes by looping through an array, but I keep encountering an error stating that the property length is missing from the array. (please refer to the screenshot) Here is my code in app.component.ts import { Component ...

The HttpParams do not include parameters with an empty string

I have this specific code snippet, in which I am making an API request with an empty string for the query parameter: getArticles(params?: HttpParams): Observable<any> { return this.http.get(this._articlesUrl, { params: new HttpParams() ...

Guide on assigning a class to an array of JSON objects in TypeScript

If I have an array of JSON objects, how can I cast or assign the Report class to it? console.log('jsonBody ' + jsonBody); // Output: jsonBody [object Object],[object Object] console.log('jsonBody ' + JSON.stringify(jsonBody)); // Outpu ...