Troubleshooting the "Cannot read properties of undefined" error in Angular 11 while managing API data

When attempting to retrieve data from an API and store it in an object (model) for logging in the console, it consistently returns undefined. The same issue occurs when attempting to use the data in HTML with databinding, resulting in undefined values as well. However, the data does populate correctly when logged within the subscribe function.

Here's an example of my TypeScript file:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { BannerStat } from 'src/app/models/banner.model';
import { Home, Banner } from 'src/app/models/home.model';
import { HomeService } from 'src/app/services/home.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit {
  home: Home;
  bannerList : Banner[];
  

  constructor(private homeService: HomeService) {}

  ngOnInit(): void {

    this.handleData();

    // The bannerList logs as undefined
    // When used in the HTML, it remains undefined as well
    console.log(this.bannerList);
    console.log(this.topMessage);

    
  }

  handleData(): void {
    this.homeService.getHomeObject<Home[]>().subscribe({
        next: (response) => {
          this.home = response[0];
        },
        error: (err: any) => {
          console.log(err);
        },
        complete: () => {
          this.bannerList = this.home.bannersBanners;
          // Both of these log the correct data
          console.log(this.home.topMessage);
          console.log(this.bannerList)
        }
      }
    );
  }

}

The object and "list" fail to initialize on time for the ngOnInit or when the page is loaded. Even moving the "handleData()" function to the constructor did not resolve the issue. Despite researching extensively, I am unable to pinpoint the necessary changes to correct this problem...

Answer №1

The reason behind this issue is the asynchronous nature of the handleData() process.

The main issue arises from the fact that ngOnInit initiates the handleData function but does not wait for the response. As a result, it continues to log the object and list to the console (this is a common behavior in JavaScript).

Subsequently, the response from the API arrives, but it is too late to be captured by the console.log in ngOnInit.

To address this, you can modify the code by using .toPromise() and await within the ngOnInit() function, such as:

await handleData().toPromise().then(response => {console.log(response);})
.

Answer №2

In order to properly access and utilize data from the API, it is essential to create a defined home variable using the syntax home: Home = new Home();. This will allow you to assign the retrieved data accordingly. Similarly, for the banner data, you can use

bannerList:: Banner[] = new Banner[]
.

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

In TypeScript, both 'module' and 'define' are nowhere to be found

When I transpile my TypeScript using "-m umd" for a project that includes server, client, and shared code, I encounter an issue where the client-side code does not work in the browser. Strangely, no errors are displayed in the browser console, and breakpoi ...

Encountering an undefined property error while using Array.filter in Angular 2

hello everyone, I am currently faced with an issue while working on a project that involves filtering JSON data. When using the developer tools in Chrome, it keeps showing me an error related to undefined property. chart: JsonChart[] = []; charts: JsonC ...

Troubleshooting CORS problem: Angular 2 and AspNetCore WebApi encounter error with preflight response having invalid HTTP status code 401

Hello there! I am currently working on implementing a straightforward token based authentication method in an Angular 2 RC6 application against an AspNetCore WebApi project that I developed using Visual Studio 2015. If you're interested, I have uploa ...

Enter data into the appropriate columns

Within my Angular 6 application, I am creating a table with the following structure: Html: <table> <thead> <tr> <th> Property Details &nbsp; &nbsp; &nbsp; &nbsp; ...

Typescript fill() function like Laravel's fill()

One interesting feature in Laravel is the fill() method of every database model, which only assigns fields marked as "mass assignable" to the class property. (https://laravel.com/docs/5.8/eloquent#mass-assignment) public class Rectangle { protected $f ...

Error: Attempting to access properties of an undefined value while retrieving data from Firebase

Struggling with displaying data in my NextJS app. Data is being fetched from Firebase, and the interface structure is as follows: export default interface IUser { name: string; email: string; uid: string; profileImageURL: string; publicData: { ...

Access the elements within arrays without using the square brackets

I am trying to access data from a list, but I am having trouble using square brackets []. The getTalonPaie function calls the get method from the HttpClient service and returns an observable with multiple values. However, when I try to store these values i ...

The browser is failing to send cookies to the backend and is also not properly setting them initially

Greetings everyone, I am currently in the process of securing my spring boot application with HTTP only cookies, transitioning from local storage. However, I have encountered some challenges along the way that even chatGPT couldn't resolve :) Let&apo ...

Tips for arranging Angular Material cards in columns instead of rows

I am currently developing a web application using Angular, and I've encountered an issue while trying to display cards in a vertical layout rather than horizontally. My goal is to have the cards fill up the first column (5-6 cards) before moving on to ...

Struggling with object type casting in Typescript

Having issues with casting objects from an HTTP API response to Typescript. I am trying to cast the json data to a Typescript object using the "as" keyword or <Type >, but it's not working as expected. r.forEach(entry => { entry.creatio ...

The flexibility of adjusting the percentage in the ng-circle-progress feature

Currently, I am utilizing ng-cycle-progress in my Angular progress. Here is the HTML code: <circle-progress [percent]="score" [radius]="100" [outerStrokeWidth]="16" [innerStrokeWidth]="8" [outerStrokeColor]="'#78C000'" [innerStrok ...

Unexpected error encountered in Angular 2 beta: IE 10 displays 'Potentially unhandled rejection [3] SyntaxError: Expected'

Question regarding Angular 2 Beta: I am starting off with a general overview in the hopes that this issue is already recognized, and I simply overlooked something during my research. Initially, when Angular 2 Beta.0 was released, I managed to run a basic m ...

Guidelines for incorporating Context API in Material UI

Currently, I am encountering a TypeScript error while attempting to pass a property using the Context API within my components. Specifically, the error message reads: "Property 'value' does not exist on type 'String'" To provide conte ...

typescript leaflet loading tutorial

I'm attempting to replicate the basic example of loading a map with Leaflet in TypeScript, following the guidance on the Leaflet website. I am not utilizing any frameworks like Angular or React. I have installed Leaflet and types through npm. To adher ...

Universal Module Identifier

I'm trying to figure out how to add a namespace declaration to my JavaScript bundle. My typescript class is located in myclass.ts export class MyClass{ ... } I am using this class in other files as well export {MyClass} from "myclass" ... let a: M ...

What are the steps to utilize a personalized validation access form within a component?

I created a unique validator to verify if an email already exists in the database before saving a new user, however, it appears that the validator is not functioning properly. Here is my template: <form class="forms-sample" #f="ngForm" (ngSubmit)="onS ...

Angular 6's inability to subscribe to a subject from multiple components simultaneously is causing issues

Having an issue with data subscription between parent and child components and a service. When emitting data using the next method in the subject class, only the child component receives the data. In navbar.component.ts: this.messageService.setClientUser ...

Understanding the complexity of defining the type of a function can be challenging. If you're tasked with a complicated function, determining its type

Let's break it down: Dict is defined as { [key: string]: () => any } The desired return value is represented by X I am attempting to create a type for a function that: Takes in a dictionary Dict T Returns an X Now, X also functions as a functio ...

It is impossible for me to invoke a method within a function

I am new to working with typescript and I have encountered an issue while trying to call the drawMarker() method from locateMe(). The problem seems to be arising because I am calling drawMarker from inside the .on('locationfound', function(e: any ...

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 ...