Understanding Observables in Angular


Observables provide support for passing messages between publishers and subscribers in Angular. They are used frequently for asynchronous operations like:

  • User input (mouse clicks, moves, keypresses)
  • HTTP requests
  • Event handling
  • Reactive state management

Observables vs Promises:

Promises handle a single future value while observables are like streams that can deliver multiple values over time.


Creating Observables:

Observables can be created using the RxJS library:

import { Observable } from 'rxjs';

const stream$ = new Observable(subscriber => { subscriber.next('Hello');
subscriber.next('World!'); });

Subscribing to Observables:

stream$.subscribe(value => { console.log(value); });


The above would print Hello and World! - each value delivered by the observable.


Piping Operators:

You can use RxJS operators like map, filter, retry to process observables:

stream$ .filter(v => v === 'Hello') .map(v => v + ' World') .subscribe(v => console.log(v));


This prints "Hello World" by filtering and mapping the observable values.


Observables are foundational for reactive Angular applications. Learning observables unlocks powerful reactive patterns for managing state, asynchronous actions, and stream processing.


Let me know if you would like me to explain any specific observable concepts in more detail!

Comments