Extract Multiple Observables with the async pipe in Angular

Most of us might familiar with this syntax:

  • The async pipe subscribes to the heroes$ 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 the async pipe multiple times on the same observable and we don't need to use the share() 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.

Subscribe to multiple observables with *ngIf using multiple async pipes

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store