Introduction
Angular has a built-in pipe async that can be used to subscribe to an Observable or Promise and return the latest value it has emitted.
Without async pipe
Let’s see how we write the code without using the async pipe. In the following OrderComponent, we have a todo object that is fetched from the DataService using the fetchTodoById method which returns an Promise. We call the fetchTodos method in the ngOnInit lifecycle hook and assign the result to the todo property.
1 | export class OrderComponent implements OnInit { |
1 | <div> |
With async pipe
With async pipe, we don’t need to call then method on Promise, the async pipe will take care of it. We can directly assign the result of fetchTodos method to the todo property and use the async pipe in the template to subscribe to the Promise.
We need two changes in the code:
- Change the type of
todoproperty toPromise<Todo> | null. - Assign the result of
fetchTodosmethod to thetodoproperty.
1 | export class OrderComponent implements OnInit { |
Note that we use the as syntax to assign the result of the async pipe to a template variable todo.
1 | <div *ngIf="todo | async as todo"> |
Using with Observables
If using with Observable, just change the type of todo property to Observable<Todo> | null.
1 | todo: Observable<Todo> | null = null; // If using Observable |
Using with ngFor
1 | <div *ngFor="let todo of todos | async"> |
Benefits
- When use with Observables, the
asyncpipe automatically subscribes to the Observable, renders the output within the template, and then unsubscribes when the component is destroyed. - You don’t need to manually subscribe and unsubscribe. - Works with Promises as well.