2016-11-16 80 views
5

我有一個angularjs2應用程序,它接收來自我的firebase服務的jsons列表。我想訪問並顯示列表的第一個元素。訪問async數組中的元素

這是我曾嘗試

<h1>{{(chapters | async)?[0].title}}</h1> 

,給了我一個模板解析錯誤。

如何訪問異步數組的第一個元素?

回答

3

您可以使用管道這樣的:

@Pipe({ 
    name: 'first' 
}) 
export class First { 
    transform(val, args) { 
    if (val === null) return val; 
    return val[0]; 
    } 
} 

,並在你的HTML

<h1>{{ (chapters | async | first)?.title }}</h1> 

Plunker Example

+0

不錯的想法:)不應該這樣做也可以'{{(章節?.first()|異步)?。標題}}'。從未嘗試過需要導入綁定的操作符。 –

1

?(安全導航)只與.(引用操作)的作品不能與[](索引訪問運營商)

什麼可能的工作是

<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> 

} 
0

我會做這樣的:

<h1>{{((chapters | async) || [])[0]?.title}}</h1>

這是一個更通用的解決方案,適用於任何指數,不僅是第一個。