简体   繁体   中英

Angular2: Async pipe for array index

I have an observable of string Arrays const obs$: Observable<string[]> on my component as a property. While I can successfully use the async pipe on a *ngIf statement, the pipe fails when accessed via array indexer (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.

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]">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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