【问题标题】:Angular check if observable is null in template角度检查模板中的可观察对象是否为空
【发布时间】:2020-12-28 17:02:35
【问题描述】:

像这样在我的角度组件中定义了一个可观察对象。

profiles$!: Observable<Profile[] | undefined>;`

我尝试像这样在我的模板中检查这个数组的长度。

<div *ngIf="(profiles$ | async).length > 0"></div>

使用这个构造,我从打字稿编译器得到错误消息Object is possibly 'null' or 'undefined'.,这完全没问题。所以在我的 if 条件中添加一个空检查。

<div *ngIf="(profiles$ | async) && (profiles$ | async).length > 0"></div>

我仍然收到对象可能为空的相同错误。我猜编译器无法识别空检查。我的问题是如何进行空值检查以避免打字稿编译器出错。

【问题讨论】:

  • 你可以试试(profiles$ | async)?.length &gt; 0。我猜在第二个示例中,由于(profiles$ | async),编译器无法知道该值必须存在。
  • 是的,这行得通!谢谢你:)

标签: angular typescript rxjs


【解决方案1】:

如果 observable 返回 null

,就会出现问题
<div *ngIf="(profiles$ | async).length > 0"></div>

解决此问题的快速方法是使用安全导航运算符?

<div *ngIf="(profiles$ | async)?.length > 0"></div>

或者您可以将 ng-container 与 ngIf 一起使用,以防您想对 observable 的返回值进行额外检查

<ng-container *ngIf="(profiles$ | async) as result">
  <div *ngIf="result.length > 0"></div>
</ng-container>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    相关资源
    最近更新 更多