Q1. What is the async pipe?
The async pipe subscribes to an Observable or Promise and returns the latest emitted value. It automatically unsubscribes when the component is destroyed, preventing memory leaks. It''s commonly used with HttpClient observables directly in templates.
Q2. How do you use async pipe with HttpClient?
Instead of subscribing in the component, assign the observable to a property and use async pipe in template. Example:
users$ = this.http.get(''/api/users'');
Template: {{ user.name }}
Q3. What are the benefits of using async pipe?
It reduces boilerplate code by eliminating manual subscriptions and unsubscriptions. It works seamlessly with OnPush change detection strategy for better performance. It also makes the template more declarative and easier to understand.
Q4. How do you handle loading and error states with async pipe?
You can combine with other observables. Example:
data$ = this.http.get(''/api/data'').pipe(
map(data => ({ loading: false, data })),
catchError(error => of({ loading: false, error })),
startWith({ loading: true })
);
Then in template, check loading and error flags.Q5. Can you use async pipe multiple times on the same observable?
Each async pipe creates a separate subscription. For performance, it''s better to use the as keyword to store the value once. Example:
Count: {{ users.length }}
{{ user.name }}
