我的代码中有这个:
<div *ngIf="(listCount$| async) > 0 ">
但它不会通过管道,因为上面写着
Object is possibly 'null' or 'undefined'.
在ts文件中:
readonly listCount$ = new BehaviorSubject<number | undefined>(undefined);
有什么帮助吗,我可以在一行中完成吗?
这是一个异步操作,可能会导致未定义的值,这就是您出现错误的原因。如果模板条件中未定义,请提供默认值。
<div *ngIf="((listCount$| async) ?? 0) > 0 ">
或者在tsconfig.json
文件中将strictNullChecks
设置为false。
"strictNullChecks": false
演示:-https://stackblitz.com/edit/angular-ivy-kheete?file=src%2Fapp%2Fapp.component.html
您可以使用as
语法来获得干净的语法,这将允许您将listCount用作变量。此变量将作为truty/falsy参数的条件进行计算,因此(0,undefined,null,",NaN(将计算为false。
<div *ngIf="(listCount$ | async) as listCount;">hello</div>