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

Observables Basics

Values over time.

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

HTTP client returns observables. Let's understand what they are, before we go further.

  • HttpClient returns observables
  • What are they?
  • A closer look

Signal or observable?

A signal always has a current value, that you can read at any time. An observable is a stream. It delivers values over time, and only to those who subscribe. HTTP responses arrive later, so they're observables.

Signal

  • always has a valueread it any timestate

Observable

  • values over timesubscribe to receiveevents, responses

Observable words

Next delivers a value. Complete says no more values will come. Error says something went wrong. And nothing happens at all, until someone subscribes.

keyvalue
next(value)a value arrives
complete()no more values
error(err)something failed
Lazynothing runs before subscribe

A hand-made observable

This observable logs started, sends two titles, then completes. We log before subscribe. Subscribe receives each value, and the completion. Run it. Started was printed only after subscribe. Then came both titles, and done.

main.tstypescript
import { Observable } from 'rxjs';

const books$ = new Observable<string>(subscriber => {
  console.log('Started');
  subscriber.next('Dune');
  subscriber.next('Emma');
  subscriber.complete();
});

console.log('Before subscribe');
books$.subscribe({
  next: title => console.log('Got', title),
  complete: () => console.log('Done'),
});
Output
Before subscribe
Started
Got Dune
Got Emma
Done
Also uses _mode
ts

HTTP is lazy too

Get only creates the observable. Subscribe is what sends the request. We log a numbered message at each step. Run it. The server received the request, only after subscribe. And the response came last.

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

@Component({ selector: 'app-root', template: `<p>The steps are in the console.</p>` })
export class App {
  private http = inject(HttpClient);

  constructor() {
    const request = this.http.get('/api/books');
    console.log('1. Observable created, nothing sent yet');
    request.subscribe(() => console.log('3. Response received'));
    console.log('2. Subscribed, so the request was sent');
  }
}
Output
1. Observable created, nothing sent yet
2. Subscribed, so the request was sent
API GET /api/books → 200
3. Response received
Also uses _apilog
1

Summary

Observables deliver values over time, and nothing runs until you subscribe. HTTP requests work the same way. Next, creating, updating, and deleting.

Key takeaways
  • next, complete, error
  • Lazy
  • subscribe() starts it
Next up: POST, PUT and DELETE — change data on the server