Home > Net >  ERROR TypeError: Cannot read properties of undefined Angular
ERROR TypeError: Cannot read properties of undefined Angular

Time:11-02

I am bringing information from my backend, it is displayed satisfactorily on my website. But I get the errors "ERROR TypeError: Cannot read properties of undefined (reading 'url')" and "ERROR TypeError: Cannot read properties of undefined (reading 'name')".

product!: IResponseProduct;
imagesProducts: any[] = [];

ngOnInit(): void {
    let { id } = this._activatedRoute.snapshot.params;
    this._productSrv.getProduct(id).subscribe((response) => {this.product = response;});
    this._productSrv.listImagenByIdProduct(id).subscribe((response) => (this.imagesProducts = response));
}

The image and name are displayed on the web

<div  style="text-align: center;">
    <a href="#"><img [src]="imagesProducts[0].url" /></a>
    <h3 >{{product.name}}</h3>
</div>

CodePudding user response:

It is all about the Angular lifecycle hooks.

In the template you are accessing imagesProducts and product variables. However you are not defining them in ngOnInit hook as it looks like, but sometimes later (because obviously this._productSrv.getProduct(id) and this._productSrv.listImagenByIdProduct(id) are async operations).

So there are several solutions to this, one of the easiest is to use optional chaining operator.

<div class="card img-big-wrap" style="text-align: center;">
    <a href="#"><img [src]="imagesProducts[0]?.url" /></a>
    <h3 class="title">{{product?.name}}</h3>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related