Angular 8 HttpClient fails to populate array on initialization

I am currently facing an issue where I am trying to populate an array from a JSON file using HttpClient. Below is the code snippet that I am using, utilizing a simple HttpClient service in Dr:

getData() {
  this.dr.getData().subscribe(data => {
    for (const d of (data as any)) {
      this.ants.push({
        x: d.x,
        y: d.y
      });
    }
    console.log("1st log : " + this.ants);
  });
  console.log("2nd log : " +this.ants);
}

Upon checking the logs, I see the following result :

2nd log : 
1st log : [object Object],[object Object]

The challenge lies in the fact that the array initialization occurs after the second log, leading to an empty array at that point. I have the getData() function called within ngOnInit(), and I intend to utilize the initialized ant array in the showData() function:

ngOnInit() {
  this.getData();
  this.ctx = this.canvas.nativeElement.getContext('2d');
  this.showData();
}

However, similar to the observations made in the 2nd log, the array appears to be empty when executing showData(). Any insights on what might be causing this behavior and how to address it would be greatly appreciated.

Answer №1

subscribe operates asynchronously, which means it does not execute immediately when you invoke

console.log("Second log : " +this.bees);
(as it is outside of the subscription callback).

If your code relies on the outcome of

this.cat.retrieveData().subscribe
, consider relocating it within the callback function.

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

Mastering the art of utilizing Angular Material's custom-palette colors for maximum impact. Unle

I have implemented a custom material-color palette where I defined the primary and accent palettes with specific shades as shown below: $my-app-primary: mat-palette($md-lightprimary ,500,900,A700 ); $my-app-accent: mat-palette($md-lightaccent, 500,900 ...

Do TypeScript project references provide value when noEmit is used?

To enhance the speed of my editor interaction and reduce the time taken by tsc to run on my TypeScript code, I am considering implementing project references. Many teams have reported substantial performance improvements after incorporating project referen ...

Fixing the Unspecified addEventListener ErrorLearn how to resolve this error

Having recently started working with Angular, I encountered an issue with my addEventListener method not functioning as intended. My goal is to create a delete button that removes a specific array from my input. This array is nested within a mat-card tag a ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

Steps for deactivating a button based on the list's size

I am trying to implement a feature where the user can select only one tag. Once the user has added a tag to the list, I want the button to be disabled. My approach was to disable the button if the length of the list is greater than 0, but it doesn't s ...

Code shared among several angular4 modules

Within my company, we are facing a challenge where there are multiple angular4 modules within a single Intellij project that contain duplicated common code. This includes Angular components, assets such as images and fonts, and dependencies like bootstrap ...

How to Retrieve Rectangle Positions on a Canvas

I am facing a specific scenario: I have created a rectangle on the canvas. By using the mouse wheel, the user can zoom in and out based on the position of the mouse cursor. Below is the TypeScript code for zooming: this.context?.clearRect( 0, 0 ...

Creating an RxJS subject in Angular 2: A step-by-step guide

Creating an Observable in my Angular component is as simple as the following code snippet: ... ... import { Observable } from 'rxjs/Observable'; .. ... let observable = new Observable( function subscribe(observer) { observer.next(1); ...

Guide to employing Axios types in project declaration files

When working on my project's type declaration file, I encountered a dilemma with using Axios types as part of my own types. The issue lies in the fact that all declarations for Axios are exported from their official repository. I specifically need to ...

What is the process for generating an array of objects using JavaScript?

I am struggling to create an array of objects using JavaScript and facing errors with new lines added where I need to split the messages and collect row numbers. The row numbers should be comma-separated if it is a repetitive error message. I found a solu ...

What events can cause all store states to be loaded when the page is altered?

I am currently utilizing ngrx/store, ngrx/effects, and ngrx/router. The implementation of my effects is structured as follows: @Effect() loadOneProduct$ = this.updates$ .whenAction(LOAD_ONE_PRODUCT) .switchMap(() => this.productService.loadOn ...

What are the steps to code this in Angular14 syntax?

Here's the code snippet: constructor(obj?: any) { this.id = obj && obj.id || null; this.title = obj && obj.title || null; this.description = obj && obj.description || null; this.thumbnailUrl = obj && obj.thumbnailUrl || null; this. ...

How Typescript allows variables to act as references to other variables

Imagine having a component with aliases for user data. This approach allows for shorter and cleaner variable names, making the code easier to read: @Component({ selector: 'my-view', templateUrl: './view.component.html', sty ...

How can I effectively utilize the Angular router to share routes among various named outlets?

My application requires displaying the same components or routes in multiple areas of the interface. This means allowing users to show certain components in various locations based on their selection, such as side panels or bottom right panels. In my situ ...

Use Angular to trigger a method when the Enter key is pressed, passing the current input text as a parameter

I need to extract the text from an input field and pass it to a method. Here is the code: index.component.html <input type="text" (keyup.enter)="sendData()" /> index.component.ts sendData() { console.log(The text from the input field); } Can ...

Ways to add parameters to each external URL using Angular

Seeking thoughts on implementing a feature in Angular to append a parameter to all external URLs or URLs from a specific domain. Let's take as an example. If I were using jQuery, I could achieve this on document ready by doing something like: $(‘ ...

The initial click may not gather all the information, but the subsequent click will capture all necessary data

Issue with button logging on second click instead of first, skipping object iteration function. I attempted using promises and async await on functions to solve this issue, but without success. // Button Code const btn = document.querySelector("button") ...

What is the best approach to defining a type for a subclass (such as React.Component) in typescript?

Can someone help me with writing a type definition for react-highlight (class Highlightable)? I want to extend Highlightable and add custom functionality. The original Highlightable JS-class is a subclass of React.Component, so all the methods of React.Com ...

How can I verify the existence of a route in Angular 2?

Is there a way to verify the existence of a route within an Angular project without redirecting? For instance, if a user enters http://localhost:4200/#/timestamp in the URL bar and the route for timestamp does not exist in the project, how can this be ch ...

Angular allows for the use of the ngIf condition within nested loops to control the display of

I'm currently working on implementing a navigation side menu using Angular with 3 levels of submenus. Below is the code I have tried: <ul class="nav metismenu" id="side-menu" *ngIf="menulist.length != 0"> <li *ngFor="let menu1 of menuli ...