[英]Angular2: Async pipe for array index
我的组件上有一个可观察的字符串数组const obs$: Observable<string[]>
作为属性。 虽然我可以在*ngIf
语句上成功使用async
管道,但是通过数组索引器(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 $的实例是在组件的构造函数中设置的,因此,当模板与数据绑定时,obs $不应是未定义的。
如何正确访问模板中的数组元素?
这可能有效
<img [src]="(obs$ | async) ? (obs$ | async)[0] : null">
我会在此级别尝试Elvis运算符,因为开始时您的数据是不确定的:
<img [src]="(obs$ | async)?[0]">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.