Access an element in an asynchronous array

I have an angularjs2 application that gets a jsons list from my firebase service. I want to get and display the first element of a list.

Here is what I tried

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

which gives me an error parsing the template.

How do I access the first element of an async array?

+5
source share
3 answers

You can use a channel like this:

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

and in your html

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

Plunger example

+3
source

? (safe navigation) only works with . (dereference operator), not with [] (index access operator)

What might work

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

but I'm not sure if chapters signed twice. In this case, this will not be a good solution. Angular2 does some deduplication in template bindings, but not sure about | async | async .

Another approach would be to assign the result to a property

 ngOnInit() { this.chapters.subscribe(val => this.captersResult = val); } 
 <h1>{{(chaptersResult?.length && chaptersResult[0].title}}</h1> } 
+1
source

I would do it like this:

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

This is a more general solution, works for any index, and not just in the first place.

0
source

Source: https://habr.com/ru/post/1259804/


All Articles