RxJS Basics & Observables
RxJS is a library for reactive programming using Observables. Angular uses RxJS extensively to handle asynchronous events, HTTP calls, and route changes.
1 Observables vs Promises
Unlike standard JavaScript Promises, RxJS Observables are highly flexible:
- Multiple Emissions: Promises emit a single value and resolve once. Observables can emit multiple values over time.
- Lazy Execution: Observables do not run until you call
subscribe(). - Cancellable: You can cancel active asynchronous requests by calling
unsubscribe(). - RxJS Operators: Provide powerful methods to transform, filter, and combine data streams (e.g.
map,filter,catchError).
2 Managing Observable Subscriptions
To display data from an Observable, you can either subscribe manually or use Angular's built-in **`async`** pipe:
TypeScript — Observable Handling
import { Component, OnInit, OnDestroy } from '@angular/core';
import { interval, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-ticker',
template: `Ticks: {{ tickValue }}
`
})
export class TickerComponent implements OnInit, OnDestroy {
private sub: Subscription | null = null;
tickValue: string = '';
ngOnInit() {
const customObservable = interval(1000).pipe(
map(val => 'Seconds active: ' + val)
);
// Subscribe to start stream
this.sub = customObservable.subscribe(msg => {
this.tickValue = msg;
});
}
ngOnDestroy() {
// Unsubscribe to prevent memory leaks
if (this.sub) {
this.sub.unsubscribe();
}
}
}
3 Code Challenge
Challenge: Research Angular's
async pipe. Write an explanation of how using it in your HTML template (e.g. *ngIf="data$ | async") automatically handles subscription cleanups for you.