Angular encountered an error when trying to access the property "fruits" of an undefined object

When working with Angular, I encountered an issue where I received the error message "cannot read property 'fruits' of undefined." Within my class definition, I have included the following:

export class MyClass implements OnInit {

fruits: any[];

doSomething() {
this.myArray.forEach(function(m) {
  const my = { test: true };
  this.fruits.push(my);
  }
}

Since I am considering adding different types to my array, I refrained from defining an interface. What could be causing this problem?

Answer №1

To gain access to this feature, arrow functions are the way to go:

fruits: any[] = [];

doSomething() {
  this.myArray.forEach(m => {
    const my = { test: true };
    this.fruits.push(my);
  }
}

By using arrow functions, you can ensure lexical binding which allows for accessing this from the object context itself (the 'outer' scope). Find out more about it here.

Answer №2

In order to start, you need to set up the fruits

export class myClass implements OnInit {

    public myArray: string[] = ['banana', 'Apple, 'Kumquat']
    public fruits: {test: boolean}[] = [];

    constructor() {}

    ngOnInit() {}

    public doSomething(): void {

      let my: any = {}; 

      this.myArray.forEach( m => {
        my = { test: true };
        this.fruits.push(my);
      });
    }
}

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

Sharing the label element as a prop in React component

I encountered the following code snippet: <div className="input-field"> <label htmlFor="timeObjective">Time Objective</label> <FrequencySet label='label'/> //HERE </div> My goal is to tra ...

The necessary package required for my library is missing (@angular/material/core not found)

I have developed a custom Angular library called @foo/bar, and it has the following dependencies: "peerDependencies": { "@angular/common": "^10.0.14", "@angular/core": "^10.0.14" }, "depend ...

The sorting of objects by Lodash is not accurate

My aim is to arrange objects based on a specific property (price). var arr = [{ name: 'Apple', price: '1.03' }, { name: 'Cherry', price: '0.33' }, { name: &apo ...

Malformed PHP Array Structure

I am facing an issue with formatting the results of my query in an array and then encoding it into JSON. I want the data to be structured like this: array[0] = project1, project2, project3; array[1] = item1, item2, item3; However, currently, my data ...

Upgrading from Angular 5 to Angular 7: A seamless migration journey

Following my migration from Angular 5 to Angular 7, I encountered an issue with RxJs operations such as observables and @ngrx/store. Here is the error message I received: ERROR in node_modules/@ngrx/store/src/actions_subject.d.ts(2,10): error TS2305: Mo ...

Using TypeScript to call a class method from within another function

Currently, I am working on an Angular 2 application and struggling to grasp the concept of TypeScript's this scope. Within my TypeScript class named SharedService, there is a function called handleError. If this function encounters a 401 status, I wa ...

Similar to LINQ's Enumerable.First(predicate) method but with a slightly different syntax, this

When working with JavaScript, we often encounter situations where we need to find the first matching element based on certain conditions. Take for example this code snippet: function process() { var firstMatch = ['a', 'b', 'c&ap ...

What is the best way to ensure that the base class Resolver finishes before allowing the derived class Resolver to execute?

I have a situation where many of my resolvers (@angular/router Resolve) need to query the same data before executing their route-specific queries. To streamline this process, I want to create a resolver base class that resolves the initial data before the ...

Extensible generic type/interface in Typescript

Looking to create a versatile base interface or type that can adapt its properties based on the generic object it receives. It might look something like this: interface BaseObject<Extension extends object = {}>{ a: string; b: string; {...Ext ...

Creating a custom decision tree in Angular/JS/TypeScript: A step-by-step guide

My current project involves designing a user interface that enables users to develop a decision tree through drag-and-drop functionality. I am considering utilizing GoJS, as showcased in this sample: GoJS IVR Tree. However, I am facing challenges in figuri ...

How to Utilize Class Members in a Callback Function in Angular 12 with Capacitor Version 3

When I click the "Device Hardware Back Button" using Capacitor 3.0, I'm trying to navigate to the parent component with the code below. The device back button is working correctly, but I'm facing an issue where I can't access class members i ...

Uh oh! We encountered an error: Uncaught (in promise): Error: No routes found for the provided URL segment

There seems to be an issue with the router in my Angular application. I have successfully deployed it on an Apache server for production, and it is being served from the URL www.domain.com/clientng. Everything works fine, but I encounter an error in the br ...

Steps to troubleshoot a simple function that manages asynchronous tasks

Looking to develop a versatile function that can handle async functions, execute them, and catch any errors that may arise. Coming from a javascript background, I initially managed to create a function that did just this. However, my attempt to enhance it ...

Organized modules within an NPM package

I am looking to develop an NPM package that organizes imports into modules for better organization. Currently, when I integrate my NPM package into other projects, the import statement looks like this: import { myFunction1, myFunction2 } from 'my-pac ...

Struggling with the TypeScript generic syntax for the GroupBy function

Struggling to figure out where I'm going wrong with this TypeScript signature after spending some time on it. I've been working on a group by function: const group = <T>(items: T[], fn: (item: T) => T[keyof T]) => { return items.re ...

Steps for managing files in Ionic Native: creating, reading, and writing them

Struggling to find proper examples for file operations like creating, reading, and writing text or logs into a file? I've done a lot of research but haven't stumbled upon any suitable solutions. The examples provided in this link seem helpful, ho ...

Unexpected identifier error: Typescript interface name syntax is incorrect

I am currently learning Typescript and still navigating my way through it. I have extensively searched for a solution to the issue I am facing, but couldn't find one, hence I am seeking help here. The problem lies in a SyntaxError at the interface nam ...

Child component received an incorrect input value

Utilizing both the "YearComponent" and "StatPeriod" components has presented some challenges for me. Within my YearComponent, I invoke StatPeriod as follows: <app-save-stat-period [dateBegin]="dateBegin" [dateEnd]="dateEnd" byMonth bestNAverage></ ...

Different Categories of Array Deconstruction

While iterating through an array, I am utilizing destructuring. const newArr = arr.map(({name, age}) => `${name} ${age}`) An error occurs in the above code stating: Binding element 'name' implicitly has an 'any' type To resolve th ...

A guide on how to initiate a click event in Angular 5 using JQuery

I am trying to trigger a click event for each element based on its id, but it doesn't seem to be working. Below is the code I am using: ngOnInit() { this.getProductsLists(); } getProductsLists() { this.supplierService.getProductLists() .sub ...