Signals and Observables Together

toSignal turns an observable into a signal, subscribing straight away and unsubscribing when the component goes, so a template reads API data like any signal. For loading and error states, subscribe and set signals for the data, the loading flag and the message.

Journeyman · Angular · Updated

After this lesson you can

  • Turn an observable into a signal with toSignal, with an initial value
  • Show loading and error states while calling an API

Key takeaways

  • toSignal turns an observable into a signal: it subscribes straight away, and unsubscribes when the component is destroyed.
  • Give toSignal an initialValue, such as an empty list, so the template has something to show until the answer arrives.
  • To show loading and error states, subscribe and set your own signals for the data, the loading flag and the error message.
  • Turn the loading flag off in both next and error, and show exactly one state with @if ... @else if ... @else.

Templates read signals; HttpClient returns observables. Angular has a bridge between the two.

toSignal

toSignal turns an observable into a signal:

import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Category, CategoryApi } from './category-api';

@Component({
  imports: [],
  selector: 'app-category-menu',
  template: `
    <ul class="nav">
      @for (category of categories(); track category.categoryId) {
        <li class="nav-item"><a class="nav-link" href="#">{{ category.categoryName }}</a></li>
      }
    </ul>
  `,
})
export class CategoryMenu {
  protected readonly categories = toSignal(inject(CategoryApi).getAll(), { initialValue: [] as Category[] });
}
  • toSignal(observable, ...) subscribes straight away, and the signal holds the latest value the observable sent.
  • initialValue is the signal's value until the answer arrives: an empty list, so the template has something to loop over. ([] as Category[] tells TypeScript what kind of empty list it is.)
  • It unsubscribes when the component is destroyed, so there's nothing to clean up.

No ngOnInit, no subscribe, no callback: one line, and the template uses categories() like any other signal.

Loading and errors

toSignal is perfect when you just need the data. But a real page should also say "Loading…" while it waits, and something helpful if the API fails. For that, keep three signals, and set them from subscribe:

import { Component, inject, OnInit, signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { Category, CategoryApi } from './category-api';

@Component({
  imports: [],
  selector: 'app-category-page',
  template: `
    @if (loading()) {
      <p>Loading the categories...</p>
    } @else if (error()) {
      <p class="text-danger">{{ error() }}</p>
    } @else {
      <ul class="list-group">
        @for (category of categories(); track category.categoryId) {
          <li class="list-group-item">{{ category.categoryName }}</li>
        }
      </ul>
    }
  `,
})
export class CategoryPage implements OnInit {
  private readonly api = inject(CategoryApi);
  protected readonly categories = signal<Category[]>([]);
  protected readonly loading = signal(true);
  protected readonly error = signal('');

  ngOnInit() {
    this.api.getAll().subscribe({
      next: categories => {
        this.categories.set(categories);
        this.loading.set(false);
      },
      error: (error: HttpErrorResponse) => {
        this.error.set(`Sorry, the categories couldn't be loaded (${error.status}).`);
        this.loading.set(false);
      },
    });
  }
}

The page shows Loading the categories... at first. Then, either the list, or, if the API answers with an error, Sorry, the categories couldn't be loaded (500). If the API isn't running, the proxy answers for it with 502 Bad Gateway, so the message says (502). And when the browser gets no answer at all, from anyone, the status is 0.

The template's @if ... @else if ... @else shows exactly one of the three states, so the user always knows what's going on.

Which to use?

Use When
toSignal(...) You need the data, and an empty list (or undefined) while it loads is fine
subscribe and your own signals You want to show loading and error states, or do something when the answer arrives
subscribe with no signals Sending something, such as a post or delete, then reacting to the answer

Check yourself

2 questions to try on the lesson page.

So what

Signals for the page, observables for the API, and toSignal or a careful subscribe between them. Show what's loading, say what went wrong, and the page never leaves the user guessing.

Key terms

Cheat sheets