Observables & RxJS Basics

RxJS (Reactive Extensions for JavaScript) is an independent library that Angular heavily integrates to handle complex asynchronous tasks natively. Instead of using JavaScript Promises, Angular relies on Observables.

Promises vs. Observables

  • Promises: Emit a single value (or fails) once, and immediately terminate. You cannot cancel a Promise in flight natively.
  • Observables: Can emit multiple values continuously over time (like a water hose streaming data). Outstanding requests CAN be proactively canceled, preventing memory leaks!

The Power of Operators (pipe)

Before data gets to your Component, you can intercept the Observable stream and mutate, filter, or delay the data using RxJS Operators.

import { map, filter } from 'rxjs/operators';

this.apiService.getSystemLogs()
  .pipe(
    // 1. Only allow logs marked as 'ERROR' to pass through the pipe
    filter(log => log.type === 'ERROR'),
    // 2. Map the object to just return the error message text
    map(log => log.message.toUpperCase())
  )
  .subscribe({
    next: (data) => console.log("Critical Error:", data)
  });

Memory Leaks and Unsubscribing

Because Observables can stream infinitely (like listening for mouse clicks or websockets), if a Component is destroyed but the subscription is left open, it causes massive Memory Leaks. You must always unsubscribe() from continuous observables in the ngOnDestroy Hook cleanly!

this.mySub = this.stream$.subscribe(...);
// Later...
this.mySub.unsubscribe();

Async Pipe in HTML

A brilliant Angular trick allows you to subscribe directly in the HTML template. Angular automatically handles subscribing—and perfectly unsubscribing—for you! This leads to immaculate, memory-leak-free code.

// .ts class
// The $ is a naming convention telling developers "This variable is an Observable stream"
users$: Observable<User[]> = this.api.getUsers();

// .html template
<ul>
  <!-- The 'async' pipe magically subscribes in HTML! -->
  <li *ngFor="let u of users$ | async">
    {{ u.name }}
  </li>
</ul>

Subjects & BehaviorSubjects

A Subject is a special type of Observable that allows values to be multicasted to many Observers (subscribers) globally. A BehaviorSubject is a Subject that "remembers" the very last emitted value, making it perfect for holding application State (like exactly which User is currently logged in).

Conclusion

RxJS is arguably the steepest learning curve in Angular, but once mastered, you can handle incredibly complex data orchestration safely. Next, we look at the lifecycle timings of Angular Components in Lifecycle Hooks.