Mar*_*kus 3 rxjs typescript angular
我在我的角度分量中有一个像这样定义的可观察量。
profiles$!: Observable<Profile[] | undefined>;`
Run Code Online (Sandbox Code Playgroud)
我尝试像这样检查模板中该数组的长度。
<div *ngIf="(profiles$ | async).length > 0"></div>
Run Code Online (Sandbox Code Playgroud)
Object is possibly 'null' or 'undefined'.通过这个构造,我从打字稿编译器得到了错误消息,这完全没问题。因此,向我的 if 条件添加一个空检查。
<div *ngIf="(profiles$ | async) && (profiles$ | async).length > 0"></div>
Run Code Online (Sandbox Code Playgroud)
我仍然收到相同的错误,该对象可能为空。我猜编译器无法识别空检查。我的问题是如何进行空检查以避免打字稿编译器出现错误。
如果可观察值返回null,就会出现问题
<div *ngIf="(profiles$ | async).length > 0"></div>
Run Code Online (Sandbox Code Playgroud)
解决这个问题的一个快速方法是使用安全导航操作符?
<div *ngIf="(profiles$ | async)?.length > 0"></div>
Run Code Online (Sandbox Code Playgroud)
或者您可以将 ng-container 与 ngIf 一起使用,以防您想对可观察值的返回值进行额外检查
<ng-container *ngIf="(profiles$ | async) as result">
<div *ngIf="result.length > 0"></div>
</ng-container>
Run Code Online (Sandbox Code Playgroud)