Angular2:数组索引的异步管道

Dyn*_*lon 5 asynchronous observable typescript angular

我的const obs$: Observable<string[]>组件上有一个可观察的字符串数组作为属性。虽然我可以async*ngIf语句上成功使用管道,但通过数组 indexer 访问时管道失败(obs$ | async)[0]

例子:

<!-- evaluates the array emmitted by obs$ for truthyness -->
<div *ngIf="obs$ | async">
    <!-- only shown if obs$ emitted an array with length > 0 -->

    <!-- but this fails with error: Cannot read property '0' of null -->
    <img [src]="(obs$ | async)[0]">
</div>
Run Code Online (Sandbox Code Playgroud)

obs$ 的实例是在组件的构造函数中设置的,因此当模板是数据绑定时, obs$ 不应未定义。

如何正确访问模板中的数组元素?

Gün*_*uer 5

这可能有效

<img [src]="(obs$ | async) ? (obs$ | async)[0] : null">
Run Code Online (Sandbox Code Playgroud)


Thi*_*ier -1

我会在这个级别尝试 Elvis 运算符,因为您的数据在开始时未定义:

<img [src]="(obs$ | async)?[0]">
Run Code Online (Sandbox Code Playgroud)