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.
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.
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.
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