Encountering a "TypeError: Cannot read property 'push' of undefined" in Angular 2

I have been working on an Angular2 component where I declared an array of strings and initialized it at the same time. However, I encountered an error of 'undefined' when I tried to push data in one of the methods. I am unsure about what I might be missing!

export class MyComponent implements OnInit {

    public categoryData: string[] = [];

    ngOnInit(): void {

    }

    public loadDataFromServer() {

        let MyServerData = result.data;

        MyServerData.forEach(function (item) {
            this.categoryData.push(item.BarTitle); // error here
        });
    }
}

error

ERROR TypeError: Cannot read property 'categoryData' of undefined

Answer №1

In order to maintain the proper context of this, it is necessary to utilize an arrow function instead of a new anonymous function created with the function keyword:

MyServerData.forEach((item) => {
  this.categoryData.push(item.BarTitle); // this line will execute without errors
});

Answer №2

Try out this code snippet for successful execution:

export class MyComponent implements OnInit {

public categoryData:string[] = [];

ngOnInit(): void {

}

 public fetchDataFromServer() {

        let serverData = result.data;
        const currentData = this;
        serverData .forEach(function(item){
            currentData.categoryData.push(item.BarTitle); // issue resolved
        });
    });
}

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 pass a callback function to labelFormatter in the legend of a Highcharts chart

I am currently experimenting with integrating HighCharts into an Angular2 project using TypeScript. My goal is to customize the appearance of the legend text, adding an image next to it. I've found that HighCharts provides a labelFormatter property w ...

Encountering the "RequestDevice() chooser has been cancelled by the user" error when using Electron 17.x with Web Bluetooth

After reviewing the following StackOverflow resources: Web Bluetooth & Chrome Extension: User cancelled the requestDevice() chooser Electron Web Bluetooth API requestDevice() Error Can you manipulate web bluetooth chooser that shows after calling requestD ...

What benefits does a bundler offer when releasing packages on npm?

After working with Node.js for many years, I recently ventured into publishing my first Node.JS package for a wider audience. Feeling lost at the beginning, I turned to Google for guidance on how to do this specifically for typescript and stumbled upon thi ...

Developing a feature in Angular 4 where shared components generate new instances with each reload

My dashboard template is based on Core UI, but I have made some modifications to better suit my app. The template consists of modules, with the sidebar menu playing a crucial role in navigation. However, as my app is larger, I utilize the top menu for navi ...

Material Design Forms in Angular: A Winning Combination

I'm currently working on developing a form using Angular Material. This form allows the user to update their personal information through input fields. I am utilizing "mat-form-field" components for this purpose. However, there are certain fields tha ...

"Maximizing Space: A Guide to Setting BootStrap Navbar on the Right Side of the Page with Dropdown Width

Take a look at the image below. There is a navbar toggle button on the upper right corner of the page. When I expand it, the dropdown items occupy the entire width of the page, causing an issue where clicking anywhere within the red box triggers the dropdo ...

Leveraging TypeScript to share information between directives in AngularJS through asynchronous calls

Although I've found some scattered information on how to tackle this issue, I haven't been able to find a solid solution. In my AngularJS application, I have an asynchronous call that fetches data from a server and I need to store it in a variab ...

Angular2 poses a strange problem with ngClass

It seems like Angular is expecting me to use single quotes for the class names even if there are no hyphens in my CSS class name. I've tried everything but Angular keeps insisting on using hyphens for this specific CSS class... it's strange, or m ...

Using Angular Ionic 3 to apply the disabled attribute

I have a situation in my main.ts where I need to disable a textarea in the HTML if an object is initialized. I've attempted various methods like: ng-attr-disabled="!myObj"; ng-attr-disabled="{myObj!= null}"; and also directly using ng-disabled. I e ...

Issue with TailwindCSS @apply not compiling in Angular v12 component styles

I am a computer science student working on a project for my studies. I am currently developing a component library for the Angular framework using Angular V12. To style the components, I have decided to use Tailwindcss as it simplifies some aspects like me ...

Retrieve the document id along with the corresponding data from a collection

Retrieving data from the collection leads and displaying all documents in an HTML table. Upon clicking, I need to extract the document ID of the clicked item as it serves as the sole primary key. P.S I am able to obtain records of all documents in an arra ...

Jest's it.each method is throwing an error: "This expression is not callable. Type 'String' has no call signatures."

I've been attempting to utilize the describe.eachtable feature with TypeScript, but I keep running into an error message stating: "error TS2349: This expression is not callable. Type 'String' has no call signatures." Below is my code snippe ...

Utilizing Angular 5 DataTables Plugin: Passing Data from HTML to TypeScript Function

I am currently working with the component.html code below, which is using a DataTables plugin. The issue I am facing is that when I select rows and click the Delete button, the handleDelete() function is called. However, I am unsure of how to pass the se ...

To ensure the specificity selector for material UI in React, it is essential to include an empty CSS definition

The styling for the unselected toggle button is working smoothly. However, when you don't define an empty class selector, the style of the selected toggle button does not show: ./App.js import * as React from "react"; { render ...

Using Angular to implement conditional logic with ngSwitch

When the number is greater than 5, increase the font size to 50px using ngswitch in case. If the number is less than 2, set the font size to 15px. Unfortunately, I was unable to find a suitable syntax for this scenario, hence no code provided here. ...

Limit the selected values to calculate a partial sum

Imagine two distinct classes called professor and student: professor.ts export class Professor { id: number name: string } student.ts import { Professor } from "./professor" export class Student { ...

What is the best way to fetch the chosen item in an Angular select dropdown

I am working on a dropdown that populates with items of type ObjectA. item.component.html: <label>items list: <select formControlName="itemsCtl" (change)="onChange()"> <option *ngFor="let item of itemList" [value]="item">{{i ...

The dreaded error message [ERR_REQUIRE_ESM] has appeared, indicating that the require() function for an ES

I am currently developing a Discord bot using TypeScript and discord.js. However, when I attempted to compile the code this morning, I encountered the following error: C:\SECRET\Kostegator\dist\Util\getMeme.js:17 const node_fetch_1 ...

Having trouble retrieving my .scss bundle file from a different directory

I am trying to access my .scss file that imports all the other .scss files (they are all imported in styles.scss). Even though I have added the path to my angular cli file, the file is still not accessible and no styling is being applied to my html elemen ...

Tips for refreshing the service page in Ionic 2

One of my services is called "user-data", and its main function is to fetch "user data" when a request is received. I have a specific page that is responsible for displaying this "user data". Upon loading the page, it retrieves the data and displays it. ...