RxJS Operations in Angular

Published on Jan 02,2025 23 Views

RxJS Operations in Angular

edureka.co

Angular is a well-known front-end tool for making web apps that are both dynamic and reliable. Additionally, RxJS in Angular offers a full set of tools made to easily handle asynchronous processes and reactive programming. This combination enables developers to create efficient, responsive, and user-friendly applications that adhere to modern web standards.

This blog post will talk about how RxJS in Angular helps developers handle data streams, handle complicated asynchronous processes, and make responsive and useful apps. Let’s first understand the idea of RxJS operations and their importance in Angular programming before getting into the specifics.

What are RxJS Operations?

Reactive Extensions for JavaScript, or RxJS in Angular, is a useful tool for Angular apps that use observables to implement event-based and asynchronous programming. You can also handle, combine, change, and modify observables in many useful ways with the help of RxJS’s large operator library.

These operators are essential for enabling reactive work with asynchronous processes and data streams. Because of this, RxJS in Angular becomes an essential component of any developer’s toolbox.

Even the most complex workflows may be easily handled by developers by utilizing Angular’s RxJS capabilities. This guarantees that, regardless of how complicated the underlying processes get, applications will always be scalable and maintainable.

Uses of RxJS operations

Common RxJS Operations in Angular

1. Observable Creation

In RxJS, the process of creating observables that continuously release a stream of data is referred to as “observable creation.” A variety of techniques, such as emitting static values, modifying pre-existing data sources, or retrieving data from external APIs, can be used to build observables.

The following are a few popular techniques for producing observables:

 2. Combination Operators

RxJS provides strong operators for combining several observables, allowing developers to easily manage complicated data streams. These operators combine emissions, synchronize data, or wait for observables to finish, catering to a variety of use situations.

3. Filtering Operators

Filtering operators let you manage the flow of data by picking out or throwing away certain values based on conditions or times. These operators help clean up data lines so that they can be processed more quickly.


4. Transformation Operators

Transformation operators convert the data emitted by an observable into the desired format, allowing for more efficient data stream processing and utilization.

 5. Error Handling Operators

Operators that handle errors make sure that the observables stay stable by handling errors well or getting back to normal after they happen.

6. Utility Operators

Utility operators are made to handle additional functions like timing, debugging, and emission management without compromising the essential operation of the observable.

Steps to Create an Angular Project

Step 1: Install npm and Node.js.

To run Angular, we must install Node.js and the Node package manager.


<code>Go to<a href="https://nodejs.org/en/download/package-manager"></code>

Step 2: Install Angular CLI

To make and handle our Angular projects, we need to install the Angular command line interface.

To install Angular CLI, run the following command:


<code><span>npm install -g @angular/cli</span></code>

Step 3: Create a New Angular Project

We are now creating an Angular project since we have the Angular CLI and Node.js installed on our machine.

Type the following command to create a new project


ng new demo-app

Step 4: Go to the Project directory

We must now navigate to the project directory after creating the project.

The following command allows us to navigate into our project directory.


cd demo-app

Step 5: Run the application

We can run our app with the following code now that we’re in the project directory:


ng serve

Structure of the folder:

Dependencies:

{
"dependencies": {
"@angular/animations": "^19.0.0",
"@angular/common": "^19.0.0",
"@angular/compiler": "^19.0.0",
"@angular/core": "^19.0.0",
"@angular/forms": "^19.0.0",
"@angular/platform-browser": "^19.0.0",
"@angular/platform-browser-dynamic": "^19.0.0",
"@angular/router": "^19.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.15.0"
}
}

Common RxJS operators

Here’s an overview of several common RxJS operators and how to use them in Angular:

1. map
An observable’s values can be changed into new values using the map operator. This is frequently used to transform data in some way.
HTML:
</div>
<div><div></div>
<div><h1>Map Operator Output</h1></div>
<div><ul></div>
<div><li *ngFor="let data of outputData">{{ data }}</li></div>
<div></ul></div>
<div></div></div>
<div>
Javascript:
</div>
<div>

import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
selector: 'app-rxjs',
imports: [CommonModule],
templateUrl: './rxjs.component.html',
styleUrls: ['./rxjs.component.css']
})
export class RxjsComponent implements OnInit {
outputData: number[] = [];

ngOnInit() {
const observable = of(7, 8, 9, 10, 11);
observable.pipe(
map(data => data * 2)
).subscribe(data => {
this.outputData.push(data);
});
}
}

Output:
The below image shows the output of the code:
2. filter
The filter operator removes values from an observable based on a condition.
HTML:
</div>
<div>
<pre><div>
<h1>Filter Operator Output</h1>
<ul>
<li *ngFor="let data of outputData">{{ data }}</li>
</ul>
</div>
Javascript:
import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { of } from 'rxjs';
import { filter } from 'rxjs/operators';

@Component({
selector: 'app-filter',
imports: [CommonModule],
templateUrl: './filter.component.html',
styleUrls: ['./filter.component.css']
})
export class FilterComponent implements OnInit {
outputData: number[] = [];

ngOnInit() {
const observable = of(1, 2, 3, 4, 5, 12, 13, 18, 19, 0, 5, 7);

observable.pipe(
filter(data => data > 7)
).subscribe(data => {
this.outputData.push(data);
});
}
}

Output: 
The below image shows the output of the code:
3. mergeMap (flatMap)
The mergeMap operator combines multiple observables into a single observable by applying a function to each emitted value and flattening the resultant observables.
HTML:
<div>
<h1>Use of mergeMap Operator</h1>
<ul>
<li *ngFor="let data of outputData | async">{{ data }}</li>
</ul>
</div>
Javascript:
</pre>
import { Component, OnInit } from '@angular/core';
import { Observable, of } from 'rxjs';
import { mergeMap, toArray } from 'rxjs/operators';
import { CommonModule } from '@angular/common'; // Import CommonModule

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
standalone: true,
imports: [CommonModule], // Include CommonModule in imports array
})
export class AppComponent implements OnInit {
outputData: Observable<number[]> = new Observable();

ngOnInit() {
const observable = of(1, 2, 3, 4, 5);
const square = (data: number) => of(data * data);

this.outputData = observable.pipe(
mergeMap((data) => square(data)), // Applies the square function
toArray() // Combines results into an array
);
}
}
<pre>
Output:
The below image shows the output of the code:
4. combineLatest
When one or more observables emit a new value, the combineLatest operator combines their most recent values.
HTML:
<div>
<h2>The Example of combineLatest</h2>
<p>Latest values from observables:</p>
<ul>
<li *ngFor="let pair of combinedValues">
{{ pair[0] }} - {{ pair[1] }}
</li>
</ul>
</div>
Javascript:
</pre>
import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { Observable, combineLatest, of } from 'rxjs';

@Component({
selector: 'app-combine-latest',
imports: [CommonModule],
templateUrl: './combine-latest.component.html',
styleUrls: ['./combine-latest.component.css']
})
export class CombineLatestComponent implements OnInit {
combinedValues: [number, string][] = [];

ngOnInit() {
const observable1: Observable<number> = of(1, 2, 3, 4);
const observable2: Observable<string> = of('A', 'B', 'C', 'D');

const combinedObservable: Observable<[number, string]> = combineLatest([
observable1,
observable2
]);

combinedObservable.subscribe((pair) => {
this.combinedValues.push(pair);
});
}
}
<pre>
Output: 
The below image shows the output of the code:

Conclusion

RxJS in Angular is a strong tool for managing data streams and easily handling asynchronous programming. Developers can efficiently modify, combine, filter, and manage observables with its vast library of operators, guaranteeing the development of responsive and maintainable systems.

Developers can improve application speed, streamline even the most complicated workflows, and comply with contemporary web development standards by comprehending and applying the different RxJS functions covered in this article.

Looking to master Angular JS and build dynamic web applications? Edureka’s Angular JS Training equips you with hands-on experience in creating scalable and robust front-end solutions. Learn from industry experts, work on real-world projects, and gain the skills to excel in your web development career. Enroll now and take the next step toward becoming an Angular expert!

Frequently Asked Questions

1. What is an RxJS operator?

A function for processing and modifying data streams in observables is called a RxJS operator. It makes working with asynchronous or event-based data easier by enabling developers to carry out operations like filtering, manipulating, merging, or managing errors in a declarative manner.

2. What is the most used operator in RxJS?

The most used RxJS operator is map. It lets you change or format data streams by applying a function to each value that an observable emits. It functions with asynchronous data and is comparable to JavaScript’s Array.prototype.map().

3. How many operators are there in RxJS?

RxJS offers more than 100 operators. You may effectively handle asynchronous data streams by using these operators, which are divided into many types such as creation, transformation, filtering, combination, and utility operators.

4. What is of () in RxJS?

In RxJS, an Observable is created from a set of values using the of() operator. It completes when all of the values have been emitted, and it does so synchronously to the subscribers. Simple observables are frequently created or tested with it.

5. What is the use of Observable in Angular?

Observables are used in Angular to manage asynchronous tasks including event handling, HTTP requests, and reactive programming. Their ability to emit various values over time and their ability to manage data streams effectively enable Angular components to respond effectively to data changes.

Angular services frequently employ observables to control state and data flow throughout the application.

Upcoming Batches For Web Developer Certification Training Course
Course NameDateDetails
Web Developer Certification Training Course

Class Starts on 11th January,2025

11th January

SAT&SUN (Weekend Batch)
View Details
Web Developer Certification Training Course

Class Starts on 1st March,2025

1st March

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Building a MERN Stack App from Scratch