我有一个可观察的字符串数组 const obs$: Observable<string[]>
在我的组件上作为属性。虽然我可以成功使用 async
管道 *ngIf
语句,当通过数组索引器访问时管道失败 (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>
obs$ 的实例是在组件的构造函数中设置的,因此当模板是数据绑定(bind)时,obs$ 不应未定义。
如何在模板中正确访问数组元素?
最佳答案
这可能有用
<img [src]="(obs$ | async) ? (obs$ | async)[0] : null">
关于asynchronous - Angular 2 : Async pipe for array index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38845501/