Table of contents
1.
Introduction
2.
Observable in Angular
3.
Nature of Observable
3.1.
Key Characteristics
3.2.
Example
4.
Usage
5.
Creating an Observable
6.
Making API Integration to Check Values
7.
Types of Notifications and Description
8.
Frequently Asked Questions
8.1.
What is the primary purpose of Observables in Angular?
8.2.
How do Observables differ from Promises?
8.3.
Why is unsubscription important in Angular Observables?
9.
Conclusion
Last Updated: Jan 26, 2025
Medium

What are Observables in Angular?

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Observables in Angular are a powerful feature used for handling asynchronous events and data streams. An Observable is a core part of the Reactive Programming paradigm, which allows developers to manage complex asynchronous data flows, such as API requests, user input events, and more. In Angular, Observables are widely used with the RxJS library to deal with operations like fetching data, event handling, and form control value changes.

What are Observables in Angular?

In this article, you will learn about Observables in Angular, including their definition, how to create them, and how to subscribe to them. We will learn on how Observables can be used to handle asynchronous tasks efficiently, allowing you to manage multiple streams of data in a more declarative and manageable way.

Observable in Angular

An Observable is a representation of a data stream that can emit values over time. In Angular, Observables are extensively used for handling asynchronous operations like HTTP requests, real-time data, and event listeners. Observables enable you to subscribe to a data stream and respond when the stream emits new data.

Key features of Observables:

  • They support asynchronous programming.
     
  • Observables emit data until they are complete or unsubscribed.
     
  • You can handle multiple types of data streams, such as user inputs or HTTP responses.

Nature of Observable

Observables in Angular work on a publish-subscribe mechanism. This means that an Observable produces a data stream, and subscribers listen for changes or updates in that stream.

Key Characteristics

  1. Lazy Evaluation: Observables do not emit data until subscribed.
     
  2. Multiple Subscribers: One Observable can have multiple subscribers, all receiving the same data.
     
  3. Unsubscription: Subscriptions can be manually terminated to prevent memory leaks.

Example

import { Observable } from 'rxjs';

const observable = new Observable(subscriber => {
  subscriber.next('First value');
  subscriber.next('Second value');
  subscriber.complete();
});

observable.subscribe({
  next: value => console.log(value),
  complete: () => console.log('Completed!')
});


Output:

First value
Second value
Completed!

Usage

Observables are used in Angular for various purposes, such as:

  1. HTTP Requests: Fetching data from a server using Angular’s HttpClient.
     
  2. Event Handling: Listening to events like button clicks.
     
  3. Form Value Changes: Reacting to changes in form inputs using Angular Forms.
     
  4. WebSocket Communication: Handling real-time communication.
     

Example of using Observables in an HTTP request:

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-user',
  template: `<div *ngIf="users">{{ users | json }}</div>`
})
export class UserComponent implements OnInit {
  users: any;

  constructor(private http: HttpClient) {}

 ngOnInit() {
    this.http.get('https://jsonplaceholder.typicode.com/users')
      .subscribe(data => this.users = data);
  }
}

Creating an Observable

You can create an Observable in Angular using the Observable constructor or helper functions from RxJS like of or from.

Example of manually creating an Observable:

import { Observable } from 'rxjs';
const customObservable = new Observable(subscriber => {
  subscriber.next('Hello');
  subscriber.next('World');
  setTimeout(() => {
    subscriber.complete();
  }, 1000);
});


customObservable.subscribe({
  next: value => console.log(value),
  complete: () => console.log('Stream completed')
});


Output:

Hello
World
Stream completed

Making API Integration to Check Values

Integrating APIs using Observables is a common task in Angular applications. Below is an example:

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
  selector: 'app-data-fetch',
  template: `<ul>
    <li *ngFor="let item of data">{{ item.name }}</li>
  </ul>`
})
export class DataFetchComponent implements OnInit {
  data: any[] = [];

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.fetchData().subscribe(result => this.data = result);
  }
fetchData(): Observable<any[]> {
    return this.http.get<any[]>('https://jsonplaceholder.typicode.com/users');
  }
}

Explanation:

  • fetchData method returns an Observable.
     
  • The component subscribes to the Observable to retrieve the data.
     

Output: A list of user names fetched from the API will be displayed.

Types of Notifications and Description

Observables in Angular can emit different types of notifications:

  1. Next: Emits a value in the stream.
     
  2. Error: Emits an error if something goes wrong.
     
  3. Complete: Signals that the stream has ended.
     

Example:

const observable = new Observable(subscriber => {

subscriber.next('Data 1');
  subscriber.next('Data 2');
  subscriber.error('An error occurred!');
  subscriber.complete();
});
observable.subscribe({
  next: value => console.log('Next:', value),
  error: err => console.error('Error:', err),
  complete: () => console.log('Stream completed')
});


Output:

Next: Data 1
Next: Data 2
Error: An error occurred!

Frequently Asked Questions

What is the primary purpose of Observables in Angular?

 Observables are used to handle asynchronous data streams, such as HTTP requests and event listeners, allowing developers to manage data flow efficiently.

How do Observables differ from Promises?

 Observables can handle multiple values over time and provide more functionality, like cancellation and multiple subscriptions, unlike Promises that resolve once.

Why is unsubscription important in Angular Observables?

 Unsubscribing prevents memory leaks by terminating unused Observables.

Conclusion

In this article, we discussed the concept of Observables in Angular, their nature, usage, and how to create and work with them. Observables play a crucial role in handling asynchronous operations, making applications efficient and responsive. 

Live masterclass