Extract Multiple Observables with the async pipe in Angular
2 min readFeb 21, 2019
Most of us might familiar with this syntax:
This syntax helps us with
- The
async
pipe subscribes to theheroes$
observable and unsubscribes once the component is destroyed. - The
as
syntax gives us a template local variable with the projected value from the subscription to the observable.
Now we can use the local variable anywhere inside this element scope.
This way we reduce our code since we don't need to use theasync
pipe multiple times on the same observable and we don't need to use theshare()
operator of RxJS - While the projected value is false the loading template will render
If you want to read more I strongly recommended this article
Todd Motto — Handling Observables with NgIf and the Async Pipe
Multiple Subscriptions 😻
So now that we are familiar with the async
pipe and as
syntax lets see how we can use the multiple subscriptions and leverage it for our benefits.
Let’s break the above example to parts
In order to subscribe to multiple observables, we use this syntax*ngIf=”{key: obsarvable | async} as data”
What we actually did is creating an object with multiple keys that use the async
pipe and data
is the local template variable with reference to the object.
Note: the
*ngIf=”{}”
is always be true