Loading...

Observables in Angular

Observables in Angular are a powerful way to handle asynchronous operations, like fetching data from a server or responding to user events. They provide a stream of data that can be observed and processed over time.

What are Observables?

An Observable is a representation of any set of values over any amount of time. It's a way to handle asynchronous data streams, allowing you to react to data as it arrives.

Why Use Observables?

Observables are used for:

  • Handling asynchronous operations.
  • Managing event streams.
  • Working with data that arrives over time.
  • Simplifying asynchronous code.

Key Concepts

  • Observables and rxjs: Observables are not native to Angular or JavaScript; they come from the rxjs (Reactive Extensions for JavaScript) library, which helps manage asynchronous data.
  • Observer Pattern: rxjs uses the Observer design pattern. An Observable emits data, and an Observer (or subscriber) listens for and processes that data.
  • Subscription: An Observer must subscribe to an Observable to receive emitted data. Without subscription, the Observer won't be notified.
  • Emission and Handling: Observables emit data using the next() method. Observers handle this data using callback functions (handlers) within the subscribe() method.

Creating Observables

You can create Observables using the Observable class from rxjs (Reactive Extensions for JavaScript).

1. Creating an Observable

To create an Observable, you use the Observable constructor from rxjs.

Example: Creating a Simple Observable


    import { Observable } from 'rxjs';

    const myObservable = new Observable<number[]>(observer => {
      observer.next([1, 2, 3, 4, 5]);
    });
    

Explanation:

  • We import Observable from rxjs.
  • We create a new Observable that emits an array of numbers.
  • The observer.next() method emits the data.

2. Subscribing to an Observable

To receive data, you subscribe to the Observable using the subscribe() method.

Example: Subscribing and Handling Data


    myObservable.subscribe(
      data => {
        console.log('Received data:', data);
      }
    );
    

Explanation:

  • The subscribe() method takes callback functions to handle emitted data.
  • The data parameter in the callback function receives the emitted data.

3. Streaming Data with Observables

Observables can stream data over time using multiple next() calls and setTimeout to simulate asynchronous behavior.

Example: Streaming Data with Delays


    import { Observable } from 'rxjs';

    const streamingObservable = new Observable<number>(observer => {
      observer.next(1);
      setTimeout(() => observer.next(2), 1000);
      setTimeout(() => observer.next(3), 2000);
      setTimeout(() => observer.next(4), 3000);
      setTimeout(() => observer.next(5), 4000);
    });

    streamingObservable.subscribe(
      value => console.log('Received value:', value)
    );
    

Explanation:

  • Multiple observer.next() calls emit data over time.
  • setTimeout simulates asynchronous delays.
  • The subscriber receives each value as it's emitted.

4. Angular Component Example

Integrating Observables into an Angular component to display streamed data.

Component (app.component.ts)


    import { Component } from '@angular/core';
    import { Observable } from 'rxjs';

                @Component({
                    selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
                        })
    export class AppComponent {
      data: number[] = [];
      streamingObservable = new Observable<number>(observer => {
        observer.next(1);
        setTimeout(() => observer.next(2), 1000);
        setTimeout(() => observer.next(3), 2000);
        setTimeout(() => observer.next(4), 3000);
        setTimeout(() => observer.next(5), 4000);
      });

      getData() {
        this.streamingObservable.subscribe(value => {
          this.data.push(value);
        });
      }
    }
    

Template (app.component.html)


    <h2>Observable Data Stream</h2>
    <button (click)="getData()">Get Data</button>
    <div *ngFor="let item of data">{{ item }}</div>
    

Explanation:

  • The component creates an Observable that emits numbers with delays.
  • The getData() method subscribes to the Observable and pushes the emitted values into the data array.
  • The template displays the data using *ngFor.

Key Points

  • Observables are used to handle asynchronous data streams.
  • You can create Observables using the Observable class or other creation functions from rxjs.
  • You subscribe to an Observable to receive emitted values.
  • Always unsubscribe from Observables in ngOnDestroy() to prevent memory leaks.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!