2016-08-09 64 views
3

我有一個可觀察的字符串數組const obs$: Observable<string[]>作爲屬性在我的組件上。雖然我可以在*ngIf語句上成功使用async管道,但通過數組索引器(obs$ | async)[0]訪問管道時管道會失敗。Angular2:數組索引異步管道

例子:

<!-- 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 $不應當模板數據綁定不確定的。

如何正確訪問模板中的數組元素?

+0

目前已經已經提交了[錯誤報告](HTTPS ://github.com/angular/angular/issues/10293) - 問題將在RC.5中修復 – rinukkusu

+0

本身不重複;如果您想遍歷數組,則重複答案中的解決方案僅適用於(使用ngFor);沒有解決方案直接通過已知索引來訪問數組 – Dyna

回答

0

我會嘗試在這個級別的貓王操作,因爲你的數據在開始時未定義:

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

「?」和「??」(實際的elvis操作符)都不起作用。此外,我不明白爲什麼'obs $'應該是undefined,如果在* ngIf塊中使用的話 – Dyna

+1

這個問題將在RC.5中修復 - 參見[bug報告](https://github.com/angular/) angular/issues/10293) – rinukkusu

+0

我已升級到RC5(昨天發佈),問題仍然存在。這兩個都不是貓王運營商?也沒有一個問號可以用於數組索引。 – Dyna

2

這可能會實現

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

事實上,我幾乎可以肯定它會起作用,但我找到了這些主題以找到比三元操作符更優雅的解決方案。但是,嘿,我們不能總是爲這種細節失去太多時間,所以我現在就用這個​​。 – Alex