Loading

Quipoin Menu

Learn • Practice • Grow

angular / Async Pipe with HTTP
tutorial

Async Pipe with HTTP

In Angular, the async pipe is a powerful tool that automatically subscribes to Observables in templates and handles unsubscription for you. It's perfect for working with HTTP requests directly in the template without manually subscribing in the component.

Without Async Pipe (Manual Subscription)
Typically, you might subscribe in the component and store the data.


@Component({...})
export class PostComponent {
posts: Post[] = [];

constructor(private dataService: DataService) { }

ngOnInit() {
this.dataService.getPosts().subscribe(data => {
this.posts = data;
});
}
}
Then in template: *ngFor="let post of posts".

With Async Pipe
You can expose the Observable directly and let the async pipe handle subscription.


@Component({...})
export class PostComponent {
posts$: Observable;

constructor(private dataService: DataService) {
this.posts$ = this.dataService.getPosts();
}
}
In template:

<ul>
<li *ngFor="let post of posts$ | async">{{ post.title }}</li>
</ul>

Handling Loading and Error States
You can combine async pipe with other observables to show loading spinners and error messages. A common pattern is to use a BehaviorSubject or create a custom observable that emits different states.


posts$ = this.dataService.getPosts().pipe(
map(data => ({ status: 'LOADED', data })),
catchError(error => of({ status: 'ERROR', error })),
startWith({ status: 'LOADING' })
);
In template:

<div [ngSwitch]="(posts$ | async)?.status">
<div *ngSwitchCase="'LOADING'">Loading...</div>
<div *ngSwitchCase="'ERROR'">Error: {{ (posts$ | async)?.error }}</div>
<div *ngSwitchCase="'LOADED'">
<ul>
<li *ngFor="let post of (posts$ | async)?.data">{{ post.title }}</li>
</ul>
</div>
</div>

Benefits of Async Pipe
  • Automatic subscription and unsubscription (no memory leaks).
  • Cleaner component code.
  • OnPush change detection works better.
  • Easier to compose with other RxJS operators.
Two Minute Drill
  • Async pipe subscribes to Observables in templates.
  • Automatically unsubscribes to prevent memory leaks.
  • Use with `| async` in template.
  • Combine with RxJS operators to handle loading/error states.
  • Leads to cleaner, more reactive code.

Need more clarification?

Drop us an email at career@quipoinfotech.com