May 26, 2020

Handling Observable in Angular using Async Pipe

Async pipe in angular helps in transforming data received asynchronously and when used along with an observable allows to:

Subscribe to the observable

Get its latest values

Marks it for onPush change detection

Automatically unsubscribes on destruction of the component

Let us now look into the implementation. Here we have a simple get method which fetches some data from an end point. Instead of subscribing an assigning the response to a variable here we will just return the data and in the component file we will use it.

Get Method for async data

Moving on to the component file, here we will create a variable of Observable type and assign it to values returned by our GET api defined in the previous step

Note: $ in the variable name is a convention to indicate an observable type.

Using Observable variable

Also Read: Custom Observable in Angular

Now in order to use the data in the front end all we need to do is transform the asyncPipeExpenses variable using the async pipe and rest is as usual as in case of the subscribe method.

Using async pipe

Advantages over Subscribe:

  • Out of box support for onPush change detection, which needs to be carried out manually when using subscribe method
  • Out of box support for unsubscribing from the observable, unlike subscribe method where this needs to be done manually using the life cycle hooks

Disadvantages over Subscribe:

  • Observable object needs to transformed every time it needs to be accessed using the async pipe

As in the example used, async pipes can be used easily along with both *ngFor and *ngIf directives and in order to be sure that the object has values we can use the “?” operator to avoid any errors.

Know more about Async Pipe here

One thought on “Handling Observable in Angular using Async Pipe

Leave a Reply

Your email address will not be published. Required fields are marked *