I am interested in delving deeper into the use cases for the async pipe in Angular.
The concept of having data asynchronously appear in the view simply by adding a pipe that subscribes to the data is quite appealing to me.
However, I have primarily encountered and correctly applied the async pipe when dealing with network requests or custom observables that contain either an array of data or a single field (such as an observable string).
For instance:
Let's consider making an API call that retrieves an array of college students.
// The data is part of a network response
$students = ...get...map...
[
{
name: "Bob OConnel",
id: 0,
description: "young..."
},
{
name: "Rick Luckard",
id: 3,
description: "young..."
},
{
name: "James Wing",
id: 2,
description: "young..."
}
]
This can be displayed in a template as follows:
<tr *ngFor="let student of $students | async">
<td>{{student.id}}</td>
<td>{{student.name}}</td>
<td>{{student.description}}</td>
</tr>
Nevertheless, sticking to the REST API approach, I haven't come across a production API call that only returns an array of data. Typically, there are additional fields at the same level as the array of data for specific reasons. Hence, I don't wish to discard these extra fields while mapping.
Therefore, instead of $students being an array, it would transform into:
// The data is in a network response
$students = ...get...map...
{
id: "69asdkasdkljasd6969"
href: "someURLrepresentingTheDatasOrigins"
length: 3
items: [
{
name: "Bob OConnel",
id: 0,
description: "young..."
},
{
name: "Rick Luckard",
id: 3,
description: "young..."
},
{
name: "James Wing",
id: 2,
description: "young..."
}
]
}
This implies that in the template, I can attach an async pipe to the $students observable, but not to its internal fields.
Clearly this doesn't function because the fields within the observables themselves...
{{$students.id| async}}
// or
<tr *ngFor="let student of $students.items | async">...</tr>
Hence, on network responses like this one, should I extract the values of the response into their individual observables if I aim to bind them asynchronously in a template? Is there a workaround if I prefer not to split the network response into multiple smaller objects?
It seems like I might be overlooking something obvious about how observables are utilized that could clarify this issue for me. Please let me know if my question requires further clarification.
UPDATE I discovered a feature here that I wasn't aware of:
Extremely useful for scenarios where some type of loading indicator should replace asynchronous data. It also helps consolidate subscriptions in one place. While it may vary based on personal preference, I believe in many instances, I would opt for placing the subscription within an *ngIf.
Is it possible to incorporate the same else template logic into an *ngFor..?