AI Hints
Home›Angular Tutorial›Observables Basics, POST, PUT and DELETE and Loading and Errors
Angular · Lesson 96 of 120

Loading and Errors

When things go wrong.

⏱ 2 min read▶ Video at 1:55:51🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Servers can be slow, and sometimes they fail. Users should see what's happening. Loading while they wait, and a clear message if it fails.

  • Slow servers
  • Failed requests
  • Tell the user

The error callback

Subscribe can take an object, with next for success, and error for failure. The error is an HTTP error response. Its status is the status code, and error holds the body the server sent.

keyvalue
next: value => ...success
error: e => ...failure
e.statuslike 500
e.errorthe server's body

A failing request

The message starts as loading. We request slash api slash fail, which always fails. Next would show the count. Error shows the status, and the server's message, instead. Run it. The server answered with five hundred. And the page shows a clear error, instead of loading forever.

app.tstypescript
import { Component, inject, signal } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-root',
  template: `<p>{{ message() }}</p>`,
})
export class App {
  private http = inject(HttpClient);
  message = signal('Loading...');

  constructor() {
    this.http.get<unknown[]>('/api/fail').subscribe({
      next: list => this.message.set(`Loaded ${list.length} books`),
      error: (e: HttpErrorResponse) =>
        this.message.set(`Error ${e.status}: ${e.error.message}`),
    });
  }
}
Output
API GET /api/fail → 500
Also uses _apilog
1

Good habits

Always show something while waiting. Always handle errors. Never leave the user staring at a page that will never finish. In the next lesson, Angular does most of this work for us.

keyvalue
While waitingshow loading
On failurea clear message
Neveran endless spinner
NexthttpResource

Summary

Use the error callback to catch failed requests, and show the user a clear message. Next, HTTP resource.

Key takeaways
  • next / error
  • e.status
  • Clear messages
Next up: httpResource — requests as signals