asynchronous - Angular 2 : Async pipe for array index

标签 asynchronous angular typescript observable

我有一个可观察的字符串数组 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/

相关文章:

javascript - Ngrx store dispatch 不接受字符串作为参数

java - 如何使用 java 异步 http 客户端 (ning) 库发布二进制字节

angular - Nginx在Docker中:位置配置不起作用

Angular RxJS mergeMap 类型

angular - 无法绑定(bind)到 'hero',因为它不是 'app-hero-detail' 的已知属性

python - Flask session 不会在 Angular App 请求之间持续存在

class - 如何在 typescript 中将一个类用作另一个类的属性的类型?

javascript - 公理 : How to run multiple requests one after the other?

javascript - 如何在页面加载后使用 JS 执行繁重的 PHP 函数以加快速度?

javascript - 是否有一种模式的名称,在该模式中,当新操作开始时,先前的异步操作会自动取消?