Snippet

Handle Errors, Loading, and Empty Data with Angular Async Pipe

AOAnonymous One· Sep 1, 20221 min read
  • #Angular
  • #TypeScript
  • #RxJS

Handle Errors, Loading, and Empty Data with Angular Async Pipe

Handle errors, loading, and empty data while using Angular async pipe with oberservables.

Example Component

Filename: admin-categories.component.ts

import { Component} from '@angular/core';
import {CategoryService} from "../../shared/services/category.service";
import {Observable, throwError} from "rxjs";
import {Category} from "../../shared/interfaces/category";
import {catchError} from "rxjs/operators";

@Component({
  selector: 'anon-admin-categories',
  templateUrl: './admin-categories.component.html',
  styleUrls: ['./admin-categories.component.scss']
})
export class AdminCategoriesComponent {
  categories$: Observable<Category[]>
  error: any;

  constructor(private categoryService: CategoryService) {
    this.categories$ = this.categoryService.getAll()
      .pipe(catchError(error => {
      this.error = error;
      return throwError(error);
    }));
  }

}

Example Component Template

Filename: admin-categories.component.html

<h1>Categories</h1>

<ng-container *ngIf="categories$ | async as categories; else loadingOrError">
  <ng-container *ngIf="categories.length; else empty">
    {{categories | json}}
  </ng-container>

  <ng-template #empty>No categories yet!</ng-template>
</ng-container>

<ng-template #loadingOrError>
  <ng-container *ngIf="error; else loading">
    <div class="error">
      <h2>Error!</h2>
      <p>Something weird happened. Keep calm and try again later.</p>
    </div>
  </ng-container>

  <ng-template #loading>
    <anon-loading></anon-loading>
  </ng-template>
</ng-template>

0 Comments

Sign in to join the conversation.

Search

Jump to a page, story or project