How to Subscribe to an Observable in Angular?
Last Updated :
06 May, 2024
In Angular, managing data streams effectively is important, especially when dealing with asynchronous operations. Observables, a core part of the RxJS library used in Angular, are powerful tools for handling these data streams. In this article, we will explore how to subscribe to Observables in Angular.
What is an Observable?
An Observable is a mechanism in RxJS used to handle asynchronous data streams, like HTTP requests, user input, etc. Observables are lazy, which means they won’t start emitting data until you subscribe to them.
How to Subscribe to an Observable?
Subscribing to an Observable means starting to listen to the stream it provides. When you subscribe, you provide functions that will be executed when the Observable emits a value, an error, or completes. Let's see how this is done with a basic example.
Steps to Create the Project
Step 1: Create a new angular project by using the following command.
ng new project-name
Step 2: Go inside the project
cd project-name
Step 3: Use the following command to start the application.
ng serve
Import HttpClientModule in the app.module.ts like below.
imports: [BrowserModule, AppRoutingModule, HttpClientModule]
And remove the auto generated HTML code form app.compoent.html
Step 4: Create a new service file inside app component using the following command.
ng g s userService
Folder Structure:

Dependencies:
"dependencies": {
"@angular/animations": "^16.1.0",
"@angular/common": "^16.1.0",
"@angular/compiler": "^16.1.0",
"@angular/core": "^16.1.0",
"@angular/forms": "^16.1.0",
"@angular/platform-browser": "^16.1.0",
"@angular/platform-browser-dynamic": "^16.1.0",
"@angular/router": "^16.1.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.13.0"
}
Approach
- In the service file create a method to return User details observable.
- We will subscribe the observable in the the app.component.ts
- Display the user details in the app.component.html
Examples:
Example 1: Fetching Data with HTTP
Imagine you have a service in Angular that fetches users data from an API using the HttpClient module. In this example I am using a dummy API service to fetch the User data.
HTML
<!-- app.component.ts -->
<h1 style="color: green">GeeksforGeeeks</h1>
<br />
<div style="
border: 1px black solid;
border-radius: 8px;
padding: 10px;
width: 500px;
">
<p>firstName: {{ usersData["firstName"] }}</p>
<p>lastName: {{ usersData["lastName"] }}</p>
<p>email: {{ usersData["email"] }}</p>
</div>
JavaScript
//app.component.ts
import { Component } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
title = 'geeks';
usersData: any = {};
constructor(private userService: UserService) {
this.getUserData();
}
getUserData() {
this.userService.getUsers().subscribe({
next: (data) => {
this.usersData = data;
},
error: (error) => {
console.error('Error fetching user:', error);
},
});
}
}
JavaScript
//userService.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
private apiUrl = 'https://dummyjson.com/users';
constructor(private http: HttpClient) { }
getUsers(): Observable<any> {
return this.http.get(this.apiUrl);
}
}
This component subscribes to the Observable returned by getUserData() and updates the userData variable with the data received.
The subscription is set up with an object containing next and error handlers:
- next: Called whenever the Observable emits data. In our case, it updates the users array.
- error: Called if there's an error during the Observable execution.
Output:

Example 2: Subscriptions with RxJS Operators
RxJS operators allow you to manipulate data streams. For example, you might want to filter or map data as it comes through the stream before it reaches the subscription. Let's see an example to include some operators:
HTML
<!-- app.component.html -->
<h1 style="color: green">GeeksforGeeeks</h1>
<br />
<div style="
border: 1px black solid;
border-radius: 8px;
padding: 10px;
width: 500px;
">
<div *ngFor="let item of usersData">
<p>firstName: {{ item["firstName"] }}</p>
<p>lastName: {{ item["lastName"] }}</p>
<p>gender: {{ item["gender"] }}</p>
<br />
<hr />
</div>
</div>
JavaScript
//app.component.ts
import { Component } from '@angular/core';
import { UserService } from './user.service';
import { catchError, map, of } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
title = 'geeks';
usersData: any = [];
constructor(private userService: UserService) {
this.getUserData();
}
getUserData() {
this.userService
.getUsers()
.pipe(
map((users) =>
users['users'].filter((user: any) => user['gender'] === 'male')
),
catchError((error) => {
console.error('Error fetching users:', error);
return of([]);
})
)
.subscribe({
next: (data) => {
this.usersData = data;
},
error: (error) => {
console.error('Error fetching user:', error);
},
});
}
}
JavaScript
//userService.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class UserService {
private apiUrl = 'https://dummyjson.com/users';
constructor(private http: HttpClient) { }
getUsers(): Observable<any> {
return this.http.get(this.apiUrl);
}
}
Output:

Similar Reads
How to iterate over Object in Angular ?
Objects consist of a set of key-value pairs, which are known as Properties. All Properties are named in JavaScript objects and the key part represents the Property name, while the value part represents the property Value. Each element(key-value pair) of the object can be utilized to perform a specif
3 min read
How to Retrieve Data using HTTP with Observables in Angular ?
Most applications obtain data from the backend server. They need to make an HTTP GET request. In this article, we'll look at making an HTTP request and map the result/response in a local array. This array can be used to display or filter the items as we want. The most important thing here is using O
4 min read
How to send REST response to html in Angular ?
In this article, we will see how to send API responses using HttpClient Module to an HTML using Angular, along with understanding the basic implementation through the examples.Angular is a JavaScript framework through which we can create reactive single-page web applications. For implementation, we
3 min read
How to bind select element to an object in Angular ?
AngularJS is a JavaScript-based framework. It can be used by adding it to an HTML page using a <script> tag. AngularJS helps in extending the HTML attributes with the help of directives and binding of data to the HTML with expressions. An Angular service is a broad category that consists of an
4 min read
How to Create an Observable with a Delay in TypeScript ?
Creating observables with delays is a common requirement in TypeScript applications, especially when dealing with asynchronous operations. To achieve this, we leverage the power of the rxjs library. What is rxjs library?The RxJS library is a powerful reactive programming library for JavaScript and T
3 min read
Angular 7 | Observables
Observables provide support for data sharing between publishers and subscribers in an angular application. It is referred to as a better technique for event handling, asynchronous programming, and handling multiple values as compared to techniques like promises.A special feature of Observables is th
7 min read
Difference between Async Operator and Subscribing to Observable
In Angular, asynchronous programming plays a crucial role in handling data streams and managing side effects. Two common approaches for handling asynchronous data with observables are using the async operator in templates and subscribing to observables in component classes. In this article, we'll se
4 min read
What is the Difference Between Promises and Observables in Angular ?
Angular is a TypeScript-based Single-Page Application framework used to create dynamic and responsive web applications. It is one of the most popular and robust frameworks. One of its key features is to handle Asynchronous Operations effectively. In Asynchronous, code is not executed sequentially ra
5 min read
How to Create a new module in Angular ?
Modules are most important when it comes to building strong and scalable Angular applications. They help organize your code, promote modularity, and improve maintainability. It encourages collaboration among developers by grouping related components, directives, pipes, and services. In this article,
3 min read
Angular 7 | Angular Data Services using Observable
Observables Observable manage async data and a few other useful patterns. Observables are similar to Promises but with a few key differences. Unlike Promises, Observables emit multiple values over time. In real scenarios, web socket or real-time based data or event handlers can emit multiple values
4 min read