We’ve covered a few different async pipe syntax tricks earlier in this newsletter, as well as why it’s important to use the async pipe to automate your subscriptions/unsubcriptions from Observables.
Today, let’s see another interesting syntax that can be very helpful when a template has multiple subscriptions, such as:
@if (firstName$ | async; as firstName) {
<div>
@if (lastName$ | async; as lastName) {
<p>First name: {{ firstName }}</p>
<p>Last name: {{ lastName }}</p>
}
</div>
}Code language: HTML, XML (xml)
We can simplify the above by creating a new object that has one property for each Observable value as follows:
@let user = { firstName: firstName$ | async,
lastName: lastName$ | async
};
<div>
<p>First name: {{ user.firstName }}</p>
<p>Last name: {{ user.lastName }}</p>
</div>
Code language: JavaScript (javascript)
That way, all our async subscriptions are in one place, and the rest of our HTML template is much more readable.