RxJS and HTTP
Work with observables, operators and HTTP requests.
What you will be able to do
- Subscribe in the template with async where possible.
- Use catchError to keep the stream alive.
- Use switchMap for type-ahead requests.
- Unsubscribe long-lived subscriptions or use takeUntilDestroyed.
In plain English
Angular’s HttpClient returns observables. An observable is lazy: nothing happens until you subscribe, often through the async pipe. Operators such as map, catchError and switchMap transform and coordinate streams.
import { Component, inject } from '@angular/core'
import { toSignal } from '@angular/core/rxjs-interop'
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs'
import { CoursesService } from './courses.service'
@Component({
selector: 'app-search',
standalone: true,
template: `<input (input)="query.set($any($event.target).value)">`,
})
export class SearchComponent {
private courses = inject(CoursesService)
query = signal('')
results = toSignal(
toObservable(this.query).pipe(
debounceTime(250),
distinctUntilChanged(),
switchMap((value) => this.courses.search(value)),
),
{ initialValue: [] as Course[] },
)
}Your turn
MediumHandle an HTTP error
Add catchError to return an empty array when the request fails.
TYPESCRIPT · starter
this.http.get<Course[]>('/api/courses')Check your understanding before moving on.
Knowledge checkQuestion 1
What does switchMap do for a type-ahead search?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.