0
0
AngularHow-ToBeginner · 4 min read

How to Create Observable in Angular: Simple Guide

In Angular, you create an Observable by importing it from rxjs and using the new Observable() constructor or helper functions like of(). Observables let you handle asynchronous data streams by subscribing to them.
📐

Syntax

To create an observable, import Observable from rxjs. Use new Observable(subscriber => { ... }) where you define how data is emitted. You can also use helper functions like of() to create simple observables.

  • Observable: The main class representing the data stream.
  • subscriber: An object used to send data with next(), signal errors with error(), or completion with complete().
typescript
import { Observable } from 'rxjs';

const observable = new Observable(subscriber => {
  subscriber.next('data');
  subscriber.complete();
});
💻

Example

This example creates an observable that emits three numbers, then completes. It shows how to subscribe to receive values and handle completion.

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 emitting')
});
Output
Received: 1 Received: 2 Received: 3 Done emitting
⚠️

Common Pitfalls

Common mistakes include not calling complete() when the stream ends, which can cause subscribers to wait forever. Another is forgetting to unsubscribe from observables that never complete, leading to memory leaks. Also, creating observables without handling errors can crash your app.

typescript
import { Observable } from 'rxjs';

// Wrong: Observable never completes or errors
const badObservable = new Observable(subscriber => {
  subscriber.next('data');
  // no complete or error called
});

// Right: Complete the observable
const goodObservable = new Observable(subscriber => {
  subscriber.next('data');
  subscriber.complete();
});
📊

Quick Reference

  • new Observable(subscriber => {...}): Create custom observable.
  • of(...values): Create observable from values.
  • subscribe(): Listen to observable data.
  • next(value): Emit data.
  • error(err): Emit error.
  • complete(): Signal completion.

Key Takeaways

Create observables in Angular by importing from rxjs and using new Observable() or helper functions like of().
Always call complete() or error() to properly end the observable stream.
Subscribe to observables to receive data and handle completion or errors.
Unsubscribe from long-lived observables to avoid memory leaks.
Use observables to manage asynchronous data streams cleanly and reactively.