this is the error saying " cannot read property 'push' of undefined " when using the code below
let deal = new Deal( 5, 'afaf', 'dafa',5,23 ) this.publicDeals.push( deal ) // gives a error saying Cannot read property 'push' of undefined(…)
The whole is shown below
export class Deal { constructor( public id: number, public name: string, public description: string, public originalPrice: number, public salePrice: number ) { } }
In another component,
import { Component, OnInit } from '@angular/core'; import { Deal } from '../deal'; import { DealService } from '../deal.service'; @Component({ selector: 'public-deals', templateUrl: 'public-deals.component.html', styleUrls: ['public-deals.component.css'] }) export class PublicDealsComponent implements OnInit { publicDeals: Deal[]; constructor( private dealService: DealService) { } ngOnInit(): void { let deal = new Deal( 5, 'afaf', 'dafa',5,23 ) this.publicDeals.push( deal ) // gives a error saying Cannot read property 'push' of undefined(…) } purchase(item){ alert("You bought the: " + item.name); } }
The "Cannot read property push of undefined" error occurs when trying to call the push() method on an undefined value. Make sure the variable on which you are calling the push() method has been initialized and set to an array before calling the method.
To fix the "Cannot read property 'push' of undefined" error with React Router, we should call the withRouter component with our route component so the history object is available in the props. import { withRouter } from "react-router"; class App extends Component { push = () => { this. props. history.
What Causes TypeError: Cannot Read Property of Undefined. Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects.
publicDeals
is not initiated;
publicDeals: Deal[] = [];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With