我從我的后端帶來資訊,它在我的網站上顯示令人滿意。但我收到錯誤“錯誤型別錯誤:無法讀取未定義的屬性(讀取 'url')”和“錯誤型別錯誤:無法讀取未定義的屬性(讀取 '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));
}
影像和名稱顯示在網路上
<div style="text-align: center;">
<a href="#"><img [src]="imagesProducts[0].url" /></a>
<h3 >{{product.name}}</h3>
</div>
uj5u.com熱心網友回復:
這都是關于Angular 生命周期鉤子的。
在模板中,您正在訪問imagesProducts和產品變數。但是,您并沒有像看起來那樣在ngOnInit鉤子中定義它們,但有時稍后(因為顯然 this._productSrv.getProduct(id) 和 this._productSrv.listImagenByIdProduct(id) 是異步操作)。
所以有幾種解決方案,最簡單的一種是使用可選鏈運算子。
<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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/345352.html
標籤:有角的
