0
0
AngularConceptBeginner · 3 min read

What is Observable in Angular: Simple Explanation and Example

In Angular, an Observable is a way to handle asynchronous data streams, like events or HTTP responses. It lets you watch for data changes over time and react when new data arrives.
⚙️

How It Works

Think of an Observable like a TV channel that broadcasts shows. You can "subscribe" to the channel to watch the shows as they air. When new shows (data) come in, you see them immediately. If you stop watching (unsubscribe), you no longer get updates.

In Angular, Observable helps manage data that arrives at different times, such as user clicks, server responses, or timers. Instead of waiting and blocking your app, it lets your app keep running and react only when new data is ready.

This makes your app more efficient and responsive, especially when dealing with things like live updates or user input.

💻

Example

This example shows how to create a simple Observable that emits numbers 1, 2, and 3, then completes. We subscribe to it and log each number.

typescript
import { Observable } from 'rxjs';

const numbers$ = new Observable<number>(subscriber => {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.next(3);
  subscriber.complete();
});

numbers$.subscribe({
  next: value => console.log('Received:', value),
  complete: () => console.log('Done receiving numbers')
});
Output
Received: 1 Received: 2 Received: 3 Done receiving numbers
🎯

When to Use

Use Observable in Angular when you need to handle data that changes over time or arrives asynchronously. Common cases include:

  • Fetching data from a server with HTTP requests
  • Listening to user input events like clicks or typing
  • Working with real-time data streams like WebSocket messages
  • Managing timers or intervals

Observables help keep your app responsive and organized by letting you react only when new data arrives, instead of constantly checking for it.

Key Points

  • An Observable represents a stream of data over time.
  • You subscribe to an Observable to receive data updates.
  • You can unsubscribe to stop receiving data.
  • Observables are useful for handling asynchronous events and data.
  • Angular uses Observables heavily, especially with HTTP and forms.

Key Takeaways

Observable lets Angular apps handle asynchronous data streams efficiently.
Subscribe to an Observable to react to new data as it arrives.
Use Observables for HTTP requests, user events, and real-time data.
Unsubscribe when you no longer need data to avoid memory leaks.
Observables make apps more responsive and easier to manage.