async pipe (Angular)

Unwraps a value from an asynchronous primitive.

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

We can use Observables without using the subscribe method in our logic by following the next snippets:

// Run our observable
const http$ = CreateHttpObservable('/api/courses');

// Let's map our results
const courses$: Observable<any[]> = http$.pipe(
  map(res => Object.values(res.payload))
);

// Let map only the beginner courses
this.beginnerCourses$ = courses$.pipe(
  map(
    courses => courses
      .filter((course: { category: string; }) => course.category === 'BEGINNER'))
);

// Let map only the advance courses
this.advanceCourses$ = courses$.pipe(
  map(
    courses => courses
      .filter((course: { category: string; }) => course.category === 'ADVANCED'))
);

We will use the async pipe in our HTML code. Unwraps a value from an asynchronous primitive.

<p *ngFor="let item of beginnerCourses$ | async">
  {{item.description}}
</p>
<hr>
<p *ngFor="let item of advanceCourses$ | async">
  {{item.description}}
</p>

Last updated