简体   繁体   English

Angular2:数组索引的异步管道

[英]Angular2: Async pipe for array index

I have an observable of string Arrays const obs$: Observable<string[]> on my component as a property. 我的组件上有一个可观察的字符串数组const obs$: Observable<string[]>作为属性。 While I can successfully use the async pipe on a *ngIf statement, the pipe fails when accessed via array indexer (obs$ | async)[0] . 虽然我可以在*ngIf语句上成功使用async管道,但是通过数组索引器(obs$ | async)[0]访问该管道时会失败。

Example: 例:

<!-- 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>

The instance of obs$ is set in the component's constructor, so obs$ shouldn't be undefined when the template is data-bound. obs $的实例是在组件的构造函数中设置的,因此,当模板与数据绑定时,obs $不应是未定义的。

How to properly access the array's elements in the template? 如何正确访问模板中的数组元素?

这可能有效

<img [src]="(obs$ | async) ? (obs$ | async)[0] : null">

我会在此级别尝试Elvis运算符,因为开始时您的数据是不确定的:

<img [src]="(obs$ | async)?[0]">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM