RxJS (Very Important) in Angular
RxJS (Reactive Extensions for JavaScript) is a core part of Angular. It allows handling asynchronous data streams using Observables, operators, and Subjects. Understanding RxJS is essential for working with HTTP requests, forms, events, and real-time data.
1. Observables & Subscribers
An Observable represents a stream of data over time. Components subscribe to it to receive values.
2. Operators
Operators transform, filter, or combine Observables.
2.1 map, filter, tap
2.2 debounceTime
Useful for search inputs to limit rapid API calls:
2.3 switchMap, mergeMap, concatMap
Used to handle nested Observables (like HTTP calls):
2.4 forkJoin
Waits for multiple Observables to complete and returns results as an array:
2.5 combineLatest
Combines latest values from multiple Observables:
3. Subjects & BehaviorSubject
Subject
A Subject is both an Observable and Observer. It can emit values to multiple subscribers:
BehaviorSubject
Keeps the latest value and emits it immediately to new subscribers:
4. AsyncPipe
Angular provides async pipe to automatically subscribe and unsubscribe from Observables in templates:
No need to manually subscribe or unsubscribe in the component.
Summary
- Observables represent asynchronous streams; subscribe to receive values.
- Operators (map, filter, tap, debounceTime, switchMap, mergeMap, concatMap, forkJoin, combineLatest) transform and control streams.
- Subjects allow multicasting of values to multiple subscribers.
- BehaviorSubject stores the latest value for new subscribers.
- AsyncPipe automatically handles subscriptions in templates.