Angular - 如何修复组件模板中的"Object is possibly 'null'"错误



我正在开发一个电子商务应用。

我有一个模板,必须呈现一个错误消息,如果提供的数量为购物车项目小于1

cartItem可以是null(或undefined),我不能(或不允许)改变它,因为它来自后端。

作为结果,我得到一个

对象可能为'null'或'undefined'.ngtsc(2533)

错误。

我试图在模板中修复这个问题,如下所示:

<ng-container *ngIf="cartItem?.qty !== null && cartItem?.qty !== undefined">
<app-alert *ngIf="cartItem?.qty < 1"
type="error"
[dismissible]='false'>
You have to specify a quantity of at least one 
</app-alert>
</ng-container>

我希望这能工作,但它没有。

这个问题的可行解决方案是什么?

从这里

<app-alert *ngIf="cartItem?.qty < 1"

编译器将警告cartItem可能是null,而您没有处理nullundefined的情况下,比较值(在当前元素中)

当您完成nullundefined检查(在顶层)时,您可以从<app-alert>元素的cartItem.qty中删除?

可以简化为:

<ng-container *ngIf="cartItem?.qty">
<app-alert *ngIf="cartItem.qty < 1"
type="error"
[dismissible]='false'>
You have to specify a quantity of at least one 
</app-alert>
</ng-container>

<ng-container *ngIf="cartItem && cartItem.qty">
<app-alert *ngIf="cartItem.qty < 1"
type="error"
[dismissible]='false'>
You have to specify a quantity of at least one 
</app-alert>
</ng-container>

相关内容

最新更新