【问题标题】:ERROR TypeError: Cannot read properties of undefined (reading 'imageUrl') Angular material错误类型错误:无法读取未定义的属性(读取“imageUrl”)角度材料
【发布时间】:2022-02-12 02:01:17
【问题描述】:

当我写这行html代码时:

<td> <img align="center" [src]="productByBarCode.imageUrl" /> </td>

控制台抛出如下错误:

ERROR TypeError: Cannot read properties of undefined (reading 'imageUrl')

imageUrl 是字符串类型,它是一个 url。我正在使用 Angular 材料。我该如何处理?

.html 文件:

<table>

        <!-- Image Column -->
  <ng-container matColumnDef="img">
    <th mat-header-cell *matHeaderCellDef></th>
    <td> <img align="center" [src]="productByBarCode.imageUrl" /> </td>
  </ng-container>

...

</table>

.ts 文件:

export class ProductDetailsComponent implements OnInit {
  public productByBarCode!: Product;
  displayedColumns = ['img', 'name', 'description', 'price', 'quantity', 'add to cart'];
  constructor(private _snackBar: MatSnackBar, private shared: SharedService, private productService: ProductService) { }

  ngOnInit(): void {
    this.shared.castByBarCode.subscribe(productByBarCode=>this.productByBarCode=productByBarCode);
...
}

【问题讨论】:

    标签: html angular typescript angular-material


    【解决方案1】:

    我只能假设您的“共享”服务在视图尝试访问它之前没有解析 productByBarCode 变量。在这种情况下,您的代码会尝试从 null 解析 imageUrl

    你可以只 *ngIf 检查productByBarCode 是否像这样是真的/假的:

    <td>
        <img *ngIf="productByBarCode" align="center [src]="productByBarCode.imageUrl" />
    </td>
    

    在此之后,如果您的图像仍然无法解析,只需 console.log 您的 productByBarCode 变量来检查里面的内容:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-24
      • 2020-05-09
      • 2019-11-16
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      相关资源
      最近更新 更多