I am unable to access the 'push' property in Angular/Typescript because it is undefined

I am encountering an issue while attempting to add an array of Funcionarios objects into a Equipa object. When trying to use the push method to add a new Funcionarios object, I receive the error message

TypeError: Cannot read property 'push' of undefined
. Despite confirming that all variables are initialized and reviewing the code multiple times, this error persists.

export class Funcionarios {
    id : Number;
    codFunc: Number;
    nomeFunc: string;

    constructor(codFunc: Number, nomeFunc: string) {
        this.codFunc = codFunc;
        this.nomeFunc = nomeFunc;
    }
}

export class Equipa {
    id : Number;
    codEquipa: Number;
    nomeEquipa: string;
    ocorFuncs: Funcionarios[] = [];

    constructor(id : Number, codEquipa: Number, nomeEquipa: string, funcs: Funcionarios[]) {
        this.id = id;
        this.codEquipa = codEquipa;
        this.nomeEquipa = nomeEquipa;
        this.ocorFuncs = funcs;
    }
}

export class TestComponent implements OnInit {

    equipa: Equipa = new Equipa(null, null, null, null);

    ngOnInit() {
        this.equipa.ocorFuncs.push(new Funcionarios(1, "qwe"));
        this.equipa.ocorFuncs.push(new Funcionarios(2, "asd"));
        this.equipa.ocorFuncs.push(new Funcionarios(3, "zxc"));
    }
}

Answer №1

Currently, your goal is to understand the task at hand.

You are attempting to add a value to a null object, which does not have a push method. If you modify the declaration line to:

equipa: Equipa = new Equipa(null, null, null, []);

it should work properly, as confirmed on stackblitz.

Answer №2

In the Equipa constructor, the ocorFuncs field is assigned with the value of the funcs parameter. If the funcs parameter is null, it overrides the default value initialized for the field. To avoid this, you should check if the parameter is null and only assign the default value if it is:

export class Equipa {
    id : Number;
    codEquipa: Number;
    nomeEquipa: string;
    ocorFuncs: Funcionarios[] = [];

    constructor(id : Number, codEquipa: Number, nomeEquipa: string, funcs: Funcionarios[]) {
        this.id = id;
        this.codEquipa = codEquipa;
        this.nomeEquipa = nomeEquipa;
        this.ocorFuncs = funcs || this.ocorFuncs;
    }
}

Answer №3

To instantiate your Equipa object, follow these steps:

new Equipa(null, null, null, null);

Since the fourth argument for initializing ocorFuncs is set to null, this line:

this.equipa.ocorFuncs.push(new Funcionarios(3, "zxc"))

is calling the push method on an improperly initialized object.

Answer №4

When you initialize your equipa, make sure to avoid setting it with null values. Instead of using

new Equipa(null, null, null, null)

consider initializing it with an empty array inside the constructor like this:

equipa: Equipa = new Equipa(null, null, null, []);

This way, when you set this.ocorFuncs = funcs;, you won't encounter any issues.

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

Transform GraphQL data into a JSON format for easier processing

I have developed a JSON api that takes JSON input from Postman and converts it into a graphql request in order to communicate with an external endpoint that exclusively accepts graphql. The conversion process is successful as I am receiving valid graphql r ...

Retrieve host and path details using Angular Universal

Is there a way to retrieve hostname and pathname information in Angular universal? On the client side app, access to this information is available through the window object. I'm looking for a solution to get this information on the server side as we ...

What is the best way to utilize mat-paginator for handling multiple requests instead of fetching all the data at once?

In our project, we have a view that pulls all the necessary information (in JSON format) for the mat-paginator display. However, there is an issue with speed as the list grows daily with thousands of new rows. One potential solution is to fetch data from ...

Is there a way to evaluate queues in C++?

I am looking to compare the sizes of 10 queues in order to determine the smallest one for inserting the next element. Creating individual if statements for each case would be extremely tedious and time-consuming. Is there a more efficient way to accompli ...

Guidance on incorporating a function as a prop in React using TypeScript

I'm currently learning TypeScript with React and ran into an issue. I attempted to pass a function as a property from my App component to a child component named DataForm. However, I encountered the following error: Type '(f: any) => any&ap ...

Use ngFor to align items to the left in your design

I am working on a div element where I need to dynamically add inputs that should form a number with a specific format. To ensure the inputs start from the left, I have applied the justify-content-end class. HTML: <div class='row justify-content-end ...

Encountering an error message in MongoDB, specifically the "BadValue" error, when attempting to utilize the $map aggregate function due to the

My goal is to convert an array of strings into an array of ObjectIds using the map function. The map function will generate an array of ObjectIds that I will use in $match to compare if the _id matches with any of the objectids present in the array using t ...

What is the process for converting a multidimensional array from PHP into JavaScript?

Recently, I've been experimenting with dygraph. To populate my graph, I fetch data via an ajax call and then need to convert the returned JSON array into a JavaScript array. My dygraph options are set up like this: series = { sample1: { ...

What steps should be taken to find a particular route when a user logs in for the first time?

I am currently working on an application using Angular 2+, Node.js, and Express.js that includes registration and login authentication functionality. How can I direct first-time users to a specific route upon login, but for all subsequent logins have them ...

Is it possible to provide unrestricted support for an infinite number of parameters in the typing of the extend function from Lodash

I am utilizing the "extend" function from lodash to combine the objects in the arguments as follows: import { extend } from 'lodash'; const foo1 = { item: 1 }; const foo2 = { item: 1 }; const foo3 = { item: 1 }; const foo4 = { item: 1 }; const f ...

"Exploring the New Feature of Angular 17: Named Router Outlets Implemented

One issue I am facing with my application is the rendering of different pages based on whether a user is logged in or not. The generic pages like the landing or logout page should be displayed within the primary router-outlet when the user is not logged in ...

Error: The 'contains' property is not available for type 'never'

I'm facing a persistent error that is making my file display in red. I attempted to include types while using useRef(null), but the error continues to persist. Could it be possible that I am assigning incorrect types? const dropdownRef = useRef(null) ...

Issue: The object is unable to be executed as a function, resulting in the failure to return an array

Currently, I am extracting table values from the UI row by row. This involves clicking on each row and retrieving the corresponding data. exports.getTableData = function(callback){     var uiArray =[];     var count;         aLib.loadCheck(c ...

Detecting the State of the Keyboard in Ionic 2

Seeking an easy way to determine if the mobile device keyboard has been opened or closed using Ionic2 and Angular2. Is there a 'keyboard-open' or 'keyboard-close' class that Ionic sends to the body/html? ...

Guide for retrieving a user object from an HTTP request

I am looking to retrieve only the user object from the request. public async getUserByHash(hash: IHash) { this.logger.log('Hash for check email accessed'); const user = await this.hashRepository.findOne({ select: ['id', ...

Looking for a solution to resolve a "repeated definition" issue

To better illustrate the issue I am facing, here is a simplified toy code example: stuff.h: #ifndef STUFF #define STUFF int a; int testarr[]={1,2,3}; #endif fcn.h: #include "stuff.h" int b[]={5,6,7}; void fcn(); main.h: #include "stuff.h" #include ...

In C++, showing a distorted representation of a 2D array retrieved from a text file through printing

Hi, I'm new to C++ and could really use some assistance with a problem I'm facing. Here's what I have so far: I've allocated memory for a 2D int array with N rows and two columns like this: int **input; input = new int *[N]; ...

Implementing a more efficient method for incorporating UUIDs into loggers

------------system1.ts user.on('dataReceived',function(data){ uniqueId=generateUniqueId(); system2.processData(uniqueId,data); }); ------System2.ts function processData(u ...

Utilize Spring to inject a personalized array of custom classes

Currently, I am facing an issue with setting an array of my custom class (XYZ[] xyz) in a bean using spring injection. When I use an array of objects i.e. (Object[] xyz), it works perfectly fine using a list collection. However, when I change it to XYZ[] x ...

The method of evaluating in-line is distinct from evaluating outside of the

What causes the compiler to produce different results for these two mapped types? type NonNullableObj1<O> = {[Key in keyof O] : O[Key] extends null ? never : O[Key]} type NotNull<T> = T extends null ? never : T; type NonNullableObj2<T> = ...