首页 > 解决方案 > Angular 8:对对象执行乘法时出现编译错误

问题描述

我在编译我的角度代码时遇到问题

  ERROR in src/app/order-details/order-details.component.html:76:55 - error TS2531: Object is possibly 'null'.

76         <div class="mat-display-1">you have to pay {{(productNumber | async ) * 90  }}  $</div>

但是我在 UI 上得到了正确的值。

我可以进行任何检查以消除此错误。

更多代码

constructor(private http : HttpClientService) {
this.productNumber=this.http.orderDetailEmitter;

}

标签: angularangular8

解决方案


您遇到的是竞争条件。您在 orderDetailEmitter observable 具有有效的整数值之前订阅它。这个是正常的。

你有两个我知道的修复。

  1. 合并值:
{{ ( (productNumber | async ) || 0 )* 90  }}
  1. 使用 ngIf
<div *ngIf="productNumber | async" class="mat-display-1">you have to pay {{(productNumber | async ) * 90  }}  $</div>

其中任何一个都可以解决问题。


推荐阅读