[英]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.