【发布时间】:2016-11-16 06:25:47
【问题描述】:
我有一个 angularjs2 应用程序,它从我的 firebase 服务接收 json 列表。我想访问并显示列表的第一个元素。
这是我尝试过的
<h1>{{(chapters | async)?[0].title}}</h1>
这给了我一个模板解析错误。
如何访问异步数组的第一个元素?
【问题讨论】:
标签: angularjs angular firebase angularfire2
我有一个 angularjs2 应用程序,它从我的 firebase 服务接收 json 列表。我想访问并显示列表的第一个元素。
这是我尝试过的
<h1>{{(chapters | async)?[0].title}}</h1>
这给了我一个模板解析错误。
如何访问异步数组的第一个元素?
【问题讨论】:
标签: angularjs angular firebase angularfire2
我会这样做:
<h1>{{((chapters | async) || [])[0]?.title}}</h1>
这是一个更通用的解决方案,适用于任何索引,而不仅仅是第一个。
【讨论】:
你可以像这样使用管道:
@Pipe({
name: 'first'
})
export class First {
transform(val, args) {
if (val === null) return val;
return val[0];
}
}
在你的 html 中
<h1>{{ (chapters | async | first)?.title }}</h1>
【讨论】:
{{ (chapters?.first() | async)?.title }}。从未尝试过需要在绑定中导入的运算符。
?(安全导航)仅适用于 .(取消引用运算符),不适用于 [](索引访问运算符)
可行的方法是
<h1>{{(chapters | async)?.length && (chapters | async)[0].title}}</h1>
但我不确定chapters 是否订阅了两次。在这种情况下,这不是一个好的解决方案。 Angular2 在模板绑定中做了一些重复数据删除,但不确定| async。
另一种方法是将结果分配给属性
ngOnInit() {
this.chapters.subscribe(val => this.captersResult = val);
}
<h1>{{(chaptersResult?.length && chaptersResult[0].title}}</h1>
}
【讨论】: