Thuta Learning
IntermediateWeb Developmentintermediate

Async Pipe

Relax. We'll talk through this in plain words — no textbook voice.

Async Pipe is used to subscribe directly to Observables and Promises inside a template. It handles unsubscribing automatically.

typescript
// component.ts
import { Observable } from 'rxjs';

export class MyComponent {
  time$: Observable<Date>;
  users$: Observable<any[]>;
  
  constructor(private dataService: DataService) {
    // Observable that emits every second
    this.time$ = new Observable(observer => {
      setInterval(() => observer.next(new Date()), 1000);
    });
    
    // Observable from HTTP request
    this.users$ = this.dataService.getUsers();
  }
}

// component.html
<p>Current Time: {{ time$ | async | date:'medium' }}</p>

<div *ngIf="users$ | async as users; else loading">
  <ul>
    <li *ngFor="let user of users">{{ user.name }}</li>
  </ul>
</div>

<ng-template #loading>
  <p>Loading users...</p>
</ng-template>
You should see
(The Observable data gets subscribed to and unsubscribed from automatically, with no memory leaks)
Async Pipe | Thuta Learning