2016-08-09 61 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