angular
  1. angular-observables

Angular Observables

Observables are a powerful tool in Angular that allow us to work with asynchronous data streams. They are used extensively in Angular applications for handling events, making API requests, and creating reactive UIs.

Syntax

import { Observable } from 'rxjs';

const myObservable = new Observable((observer) => {
  // emit data to subscribers
  observer.next('Hello');
  observer.next('World');

  // complete the stream
  observer.complete();
});

Example

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

@Component({
  selector: 'app-my-component',
  template: `
    <button (click)="fetchData()">Fetch Data</button>
    <div *ngIf="data$ | async as data">{{ data }}</div>
  `
})
export class MyComponent {
  data$: Observable<string>;

  fetchData() {
    this.data$ = this.http.get<string>('https://example.com/data');
  }
}

Output

The above example will display a button, on clicking which a request will be sent to https://example.com/data. Once the request completes, the response will be displayed on the page.

Explanation

Observables are used extensively in Angular for handling asynchronous data streams. They are used for handling events, making API requests, and creating reactive UIs. The basic structure of an observable involves creating a new observable instance, subscribing to it, and then emitting data to the subscribers.

In the above example, we have used the http service to fetch data from an external API. We have assigned the response to an observable data$, and used the async pipe to display the response on the page.

Use

Observables are used in Angular applications to handle asynchronous data streams. They are particularly useful for:

  • Handling async operations such as API requests, user input, DOM events, etc.
  • Creating reactive UIs that respond to state changes in the application.
  • Composing multiple data streams through operators like switchMap, mergeMap, filter, map, etc.

Important Points

  • Observables can be used for handling asynchronous data streams in Angular.
  • Observables can be created using the Observable class from the rxjs library.
  • There are many operators available for handling and transforming observable streams.
  • Observables can be subscribed and unsubscribed to, and can emit multiple values.

Summary

Observables are a powerful tool in Angular that allow us to work with asynchronous data streams. They are used extensively in Angular applications for handling events, making API requests, and creating reactive UIs. By using observables, we can write more efficient and performant code that can handle complex asynchronous operations with ease.

Published on: