Issue: Angular ERROR TypeError - Cannot access the property 'push' of a null value

In my code, I have a property called

category = <CategoryModel>{};
. The CategoryModel model looks like this:


export class CategoryModel {
 public name: string;
 public description: string;
 public image: string;
 public products?: ProductModel[];

constructor(name: string, desciption: string, image: string = null, products: ProductModel[]) {
    this.name = name;
    this.description = desciption;
    this.image = image;
    this.products = products;
}
}

I am trying to store the category in an Array named

categoryList: CategoryModel[] = [];
using the following code
this.categoryList.push(this.category);
. But I encountered an error saying
ERROR TypeError: Cannot read property 'push' of null
.

This is a post method where I intend to save the category in the array and then send it to the server.


export class AdminComponent implements OnInit {

  category = <CategoryModel>{};
  categoryList: CategoryModel[] = [];
  categoryProduct: ProductModel[];
  ...
  
  constructor(...) { }

  ngOnInit() {
    this.getCategory();
    this.initForm();
    console.log(this.categoryList);
  }
  ...

  getCategory() {
    this.dataStorageServiceService.getCategory()
      .subscribe(
        (cateogrys: CategoryModel[]) => {
          this.categoryList = cateogrys;
          console.log(this.categoryList)
        }
      );
  }
  
  storeCategoryList() {
    const nameCategory = this.categoryForm.value.name;
    const descriptionCategory = this.categoryForm.value.category;
    this.category.name = nameCategory;
    this.category.description = descriptionCategory;
    console.log(this.category);

    this.categoryList.push(this.category);
    this.dataStorageServiceService.storeCategoryList(this.categoryList).subscribe(

      (category: CategoryModel) => {
        category = this.category
        this.categoryList.push(category)
        console.log(this.categoryList)
      }

    )
}

...

Answer №1

To maintain scope to the outer class while calling the method from within the modal, consider changing the signature of storeCategoryList() to an arrow function:

storeCategoryList = () => {
  // your existing code
}

This adjustment should help with preserving lexical scope. Thank you!

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

Angular2/TypeScript Coding Guidelines

I am curious about the common practices and consensus among the Angular2 community when it comes to writing reusable code in TypeScript. I have gathered some information and questions related to Angular2 that I would like to discuss. Organizing Module/A ...

Running a desktop Word AddIn using Angular 11.0.5 on MS Office 2016: A Step-by-Step Guide

I am facing an issue with loading my add-ins in the Office desktop version, although it works fine on the online platform. I initially developed the AddIn using Angular 5.2.11 and it worked perfectly. However, after upgrading to Angular 11.0.5, the Add-in ...

Converting an Array of Objects into a single Object in React: A Tutorial

AccessData fetching information from the database using graphql { id: '', name: '', regions: [ { id: '', name: '', districts: [ { id: '', ...

The creation of a parameterized function that doubles as an object property

interface item { first: string; last: string; } const itemList = Item[]; updateAttribute = (index, attributeToUpdate) => { itemList[index].attributeToUpdate = "New first/last" } The snippet above showcases an interface named item with propertie ...

What is the best way to relocate the styles folder to the src folder while using nextjs, typescript, and tailwind

I am currently working with Next.js using TypeScript and Tailwind CSS. My goal is to relocate the styles folder into the src folder. I have already updated the baseUrl in my tsconfig.json file to point to the src directory, but I encountered the following ...

What is the best approach to creating an array within my formgroup and adding data to it?

I have a function in my ngOnInit that creates a formgroup: ngOnInit() { //When the component starts, create the form group this.variacaoForm = this.fb.group({ variacoes: this.fb.array([this.createFormGroup()]) }); createFormGroup() ...

The Angular Proxy seems to handle GET requests successfully, but encounters issues when it comes to

After setting up a proxy for my requests on my Angular application, I successfully managed to redirect my GET request to http://localhost:3000/api/users. However, the issue arises with my POST request as it continues to go to http://localhost:4200/api/user ...

How do you go about making a prop optional in Typescript based on a generic type?

In my app, I have a specific type with optional props based on a generic type: type MyCustomType<R extends Record<string, string> | undefined, A extends string[] | undefined> = { record: R, array: A } There is a function that directly uses ...

Is there a way to specifically target the MUI paper component within the select style without relying on the SX props?

I have been experimenting with styling the Select MUI component using the styled function. I am looking to create a reusable style and move away from using sx. Despite trying various methods, I am struggling to identify the correct class in order to direct ...

Get the final element with a for loop in Angular 2

I am currently utilizing angular 2 in conjunction with mongoDb. The service I am employing is responsible for calling the API. Here is a snippet of my code: this.at represents a token, similar to fdfdsfdffsdf... This token serves as an authorization key ...

Can anyone suggest a more efficient method for specifying the type of a collection of react components?

Picture this scenario: you are extracting data from an API and creating a list of Card components to be displayed in a parent component. Your code might resemble the following: function App() { let items = [] // How can I specify the type here to avoid ...

Guide on utilizing mat-slide-toggle to assign either a value of 1 or 0

I am utilizing the mat-slide-toggle feature from Material in a similar manner to this example https://material.angular.io/components/slide-toggle/overview The problem I am encountering is similar to the issue outlined in this link: https://stackblitz.com ...

Issue with executing a server-side function in a Next.js application

I'm encountering an issue with my Next app. I have a method in my ArticleService class that retrieves all articles from my SQL database. async getArticles(): Promise<IArticle[] | ServiceError> { try { const reqArticles = await sql< ...

Get detailed coverage reports using Istanbul JS, Vue JS, Vue CLI, Cypress end-to-end tests, and Typescript, focusing on specific files for analysis

I have a VueJS app written in Typescript that I am testing with Cypress e2e tests. I wanted to set up coverage reports using Istanbul JS to track how much of my code is covered by the tests. The integration process seemed straightforward based on the docum ...

First, download a npm package and integrate it into TSX files

Hello all, I am currently working on my very first project using React, Typescript, and ASP.NET Core. As a beginner in this technology stack, I seek your patience and understanding as I encounter challenges along the way. Right now, I'm facing an issu ...

What are the best practices for utilizing generics effectively?

A series of interfaces has been defined: export interface FormData<T extends ControlData = any> { [type: string]: T; } export type FormResult<T extends FormData> = { [type in keyof T]: T[type]; }; export interface ControlData<T = any& ...

Is it necessary for Angular to wait for the template to update before moving on to perform calculations

My goal is to animate smoothly from an auto height to zero and back. When using jQuery, I would have to manually calculate the height of the auto container, set it as a fixed height, then change it to zero allowing css transitions to take over. To revert b ...

Using TypeScript to asynchronously combine multiple Promises with the await keyword

In my code, I have a variable that combines multiple promises using async/await and concatenates them into a single object const traversals = (await traverseSchemas({filename:"my-validation-schema.json"}).concat([ _.zipObject( [&quo ...

Arranging an array of arrays based on the mm/dd/yyyy date field

Currently, I am facing an issue while attempting to sort data obtained from an API by date in the client-side view. Here is an example of the data being received: address: "1212 Test Ave" address2: "" checkNumber : "" city: "La Grange" country: "" email: ...

Using any random function as a property value in a TypeScript React Component

I am facing a challenge in my React component where I need to define a property that can accept any arbitrary function which returns a value, regardless of the number of arguments it takes. What matters most to me is the return value of the function. Here ...