[Solved] Cannot read a property push of undefined in angular

Problem

In Angular when pushing items to an Array I get “Uncaught TypeError: Cannot read property ‘push’ of undefined” error as shown below screenshot.

Cannot read a property push of undefined in angular

Code

Here is the code example where this issue occurs, ListEmployeeComponent Component class

import { Component, OnInit } from "@angular/core";
import { EmployeeService } from "../employee.service";
import { IEmployee } from "src/app/IEmployee";
import { Router } from "@angular/router";

@Component({
  selector: "app-list-employee",
  templateUrl: "./list-employee.component.html",
  styleUrls: ["./list-employee.component.css"],
})
export class ListEmployeeComponent implements OnInit {
  employees: IEmployee[];
  constructor(
    private _employeeservice: EmployeeService,
    private router: Router
  ) {}

  ngOnInit() {
    this._employeeservice.getEmployees()
.subscribe((listEmployee) => {
      	for (let i = 0; i < listEmployee.length; i++) {
        this.employees.push(listEmployee[i]);
      }
      (err) => console.log(err);
    });
  }

}
}

Interface IEmployee

export interface IEmployee{
    id:number;
    fullName:string;
    email:string;
    phone?:number;
    contactPreference:string;
}

Solution

To solve this issue Uncaught TypeError: Cannot read property ‘push’ of undefined, there is a solution given below.

Array Initialization

You have to initialize array using below

@Component({
  selector: "app-list-employee",
  templateUrl: "./list-employee.component.html",
  styleUrls: ["./list-employee.component.css"],
})
export class ListEmployeeComponent implements OnInit {
  employees: IEmployee[]=[];
  .........
}

or

You can initialize this array in ngOninit() method https://angular.io/guide/lifecycle-hooks, the line is highlighted in below code

// implement OnInit's `ngOnInit` method
ngOnInit() {
// initialize array here
this.employees=[];
this._employeeservice.getEmployees().subscribe((listEmployee) => {
      for (let i = 0; i < listEmployee.length; i++) {
        this.employees.push(listEmployee[i]);
      }
      (err) => console.log(err);
    });
  }
}

Tip: What is Array initialization in TypeScript/JavaScript Mean?

To declare and initialize an array we would use the following syntax

var array_name[:data type]; //declaration
array_name = [value_1,value_2…...value_n] //initialization

Example

var employees: IEmployee[]=[]; //employees array and type is IEmployee
or
var employees=[]; //An array declaration without the data type is to be, of the type any

Add an item to an Array

To add an item to an Array we could use push operations:
var employees=[]
employees.push('Jhon');

Default image
Shivaraju M
Over 3+ years experience in IT industry, good knowledge in . Net-based Web applications, windows applications, web services, and SPAs. I have played multiple roles related to technical delivery in multiple domains while working on over 10+ technologies. I am currently focused on continuous improvement and agile project management.

Leave a Reply