Cannot read Property push of Undefined Angular

Asked

Viewed 2,223 times

0

I have the following model:

produtosConfirmadosAnuncio.model.ts:

export class ProdutosConfirmadosAnuncio{

   idContasAnunciarB2W:[{id: number}];

}

I start it this way:

produtosConfirmadosAnuncio: ProdutosConfirmadosAnuncio[] = []

At a certain point in my application I should add an object to that Array:

if(this.contasB2W[i] == event.option.viewValue){
   console.log(this.idContasB2W[i])
   this.produtosConfirmadosAnuncio[index].idContasAnunciarB2W.push({id: this.idContasB2W[i]});
}

And then I get on the line that contains the push:

ERROR Typeerror: Cannot read Property 'push' of Undefined

In that console.log value 22 shall be printed.

  • The variable index exists?

  • Yes, I’ve figured out the problem, I’ll add an answer

1 answer

0


I resolved it that way:

I made a logic to only push if there are elements, if there are no elements still receives the object:

this.produtosConfirmadosAnuncio[index].idContasAnunciarB2W = [{id: this.idContasB2W[i]}];

And then, the next pushs that came worked normally.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.