Home/Blog/Programming/Get started with RxJS in Angular
Home/Blog/Programming/Get started with RxJS in Angular

Get started with RxJS in Angular

9 min read
Jun 17, 2021
content
What is RxJS?
Key features of RxJS
What is Angular?
Angular’s core components
Why use RxJS in Angular?
RxJS in Angular: A step-by-step example
1. Generate a new project
2. Style with CSS
3. Import reactive forms
4. Create a new component
5. Create a phone input
6. Create a FormControl property
7. Validate forms
8. Display error messages
Common RxJS patterns
RxJS Observables vs. Promises: A detailed comparison
Key differences
When to use:
Pros and cons of using RxJS in Angular
Pros
Cons
Wrapping up and next steps
Continue learning about React

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Key takeaways:

  • RxJS is a powerful library for reactive programming, widely used in Angular to handle asynchronous data streams and event-driven programming.

  • RxJS integrates seamlessly with Angular through observables, enabling efficient data flow, event handling, and reactive state management.

  • Key concepts in RxJS include observables, operators, and subjects, which provide a flexible way to handle asynchronous and event-driven logic.

  • RxJS plays a crucial role in implementing reactive forms in Angular, facilitating real-time validation and dynamic form interactions.

  • RxJS enhances asynchronous operations like HTTP requests, user interactions, and event handling, improving performance and code maintainability in Angular applications.

If you're working with Angular, you've likely come across RxJS (Reactive extensions for JavaScript)—a powerful library that simplifies handling asynchronous data streams. Whether you're dealing with API requests, user input, or real-time updates, RxJS provides a structured, declarative way to manage data flows. In this blog, we'll break down how RxJS integrates with Angular, explore key concepts, and walk through a practical implementation example.

What is RxJS? #

RxJS is a reactive programming library that helps handle asynchronous events such as user interactions, API calls, or real-time updates. In Angular, RxJS simplifies async task management, enabling developers to write cleaner, more maintainable code while efficiently managing data streams.

Reactive programming allows developers to build scalable, event-driven applications that react to data changes in real time. By exploring RxJS, you’ll learn essential techniques such as observables, operators, and concurrent programming, which are crucial for creating dynamic web applications.

Cover
Reactive Programming with RxJS

In this course, you will learn about reactive programming techniques and use them to create real-world applications. Throughout this course, you will learn important concepts of RxJS programming such as observables, operators, concurrent programming, and how to build a complete web application. Additionally, you will have the opportunity to build out applications for different real-world scenarios so that you can put what you learn into practice. You will use RxJS operators in scenarios such as the real-time earthquake visualizer and the reactive spaceship game. By the end, you will have a new skill that you can utilize to build reactive programs as well as a few new projects to add to your portfolio.

63hrs 5mins
Intermediate
55 Playgrounds
9 Quizzes

To dive deeper, check out the What is RxJS in Angular? answer on Educative.

Key features of RxJS#

RxJS has some core features that help handle async implementation:

  • Observable: RxJS observables represent a stream of values (or events) over time. They emit data (such as events or values) to which other components, like observers, can subscribe and react. Observables are lazy, meaning they do not start emitting values until a subscription occurs. In Angular, observables are widely used for handling HTTP requests, user input events, and real-time data streams.

  • Observer: The observer listens to an observable and reacts to emitted values, errors, or completion signals using methods like next(), error(), and complete(). They are the objects that subscribe to observables.

  • Subscription: A subscription triggers the observable to start emitting data.

  • Operator: An operator is a function that allows us to perform certain actions on events emitted by observables, like filtering or mapping the values.

  • Subject: A subject is the same as an EventEmitter, but with additional capabilities. It can multicast values to multiple observers, allowing it to be shared among multiple parts of an application.

  • Scheduler: A scheduler handles the execution of subscriptions. It  also controls concurrency, determining the timing and order of value emissions. It provides advanced control over async tasks.

RxJS excels at async handling with a rich set of operators for filtering, error handling, and multicasting. It is supported by both JavaScript and TypeScript, making it a perfect fit for use with Angular.

What is Angular?#

Angular is a web application framework that is built on TypeScript. It is used by many frontend developers to build single-page client applications using TypeScript and HTML. There are many Angular applications. Some popular Angular apps include Gmail, Xbox, Upwork, and PayPal. RxJS plays a crucial role in Angular for handling asynchronous operations and event-driven programming.

Angular’s core components#

There are some core components that make up the Angular framework. Let’s take a look at them:

  • Components

    Angular components are the core UI building blocks of an Angular application. Each component has:

    • an HTML template declaring what renders on the page
    • a TypeScript class defining its behavior
    • a CSS selector defining how to use the component in a template
  • Templates

    Templates are used by components. They declare how the components render on the page. Directives allow you to add additional functionalities to your templates. Directives can do many things, like allow you to modify the DOM structure. The most popular ones are ngfor and ngif.

  • Dependency injection

    Dependency injection is not a necessity when working with Angular, but it is known as a best practice. It allows you to declare the dependencies of your classes while allowing Angular to take care of the instantiation.

  • Libraries

    Libraries extend upon the base functionalities of Angular and allow you to do many different things. There are many Angular libraries available for you to use, such as:

Master observables and wrangle in RxJS without scrubbing through videos or documentation. Educative’s text-based courses are easy to skim and feature live coding environments, making learning quick and efficient.

Cover
Build Reactive Websites with RxJS: Master Observables and Wrangle

The list of requirements for frontend work keeps increasing. Websites that load quickly on shaky connections, render perfectly on mobile devices, and respond with lightning speed to user input are expected. All of these tasks require dealing with a high number of events from disparate sources, be it your Customer Relationship Management (CRM), late-breaking news, or just a chat room. Observables is a new way of thinking about managing these events, even when they may occur sometime in the future. In this course, you’ll learn how to delegate both the calls and control flow to RxJS, allowing you to focus on the rest of your application. RxJS compartmentalizes eventing flows, encapsulating each action in a single function, providing many helper operators that keep an internal state, allowing you to outsource your state worries to the library. By the end of this course, you will be able to build bigger, faster, and less-buggy applications for your users.

50hrs 30mins
Intermediate
90 Playgrounds
9 Quizzes

Why use RxJS in Angular?#

Angular leverages RxJS extensively in its core framework, including for HTTP requests, form handling, and event handling. With RxJS, we can:

  • Build scalable and performant web applications.

  • Handle asynchronous streams like API calls, user inputs, and more.

  • Write cleaner code with better separation of concerns.

  • Implement reactive forms for handling user inputs in real-time.

RxJS in Angular: A step-by-step example#

Let’s walk through how to integrate RxJS with Angular using an example where we build a phone number input field with validation.

1. Generate a new project#

To start, run npm install -g @angular/cli to install the Angular CLI. Then, create a new project using:

ng new rx-phone --routing

Note: The --routing flag sets up a basic Angular router module. If you want to leverage RxJS observables in routing, you can subscribe to Router.events for reactive route change handling.

2. Style with CSS#

The application we want to build uses Bootstrap’s CSS for visual appeal. We will begin by opening index.html. Then, let’s bring in the CSS and add the following tag to the <head> of the file:

<!-- Bootstrap (loaded from local server) -->
<link rel="stylesheet" href="http://localhost:3000/assets/bootstrap.min.css">

You’ll see some placeholder HTML in app.component.html. Remove it and add this in its place:

<div class="container">
<router-outlet></router-outlet>
</div>

3. Import reactive forms#

Since Angular doesn’t include Reactive Forms by default, we need to import the module manually. Add the following import to your app.module.ts file:

import { ReactiveFormsModule } from '@angular/forms';

Then, update the imports array in @NgModule:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms'; // <callout id="co.ng2reactiveforms.module1"/>
/* ... snip ... */
@NgModule({
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule // <callout id="co.ng2reactiveforms.module2"/>
],
declarations: [
AppComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }

4. Create a new component#

To create and configure a new component in an Angular application, follow these steps. This ensures the component is properly declared, routed, and accessible within the app.

  1. Run ng generate component phone-num and add a declaration to the routing module.
  2. Start the Angular server with ng serve.
  3. Add a route to app-routing.module.ts for the new component.
{
path: 'phone',
component: PhoneNumComponent
},

5. Create a phone input#

Open phone-num.component.ts and import FormControl and AbstractControl:

import { FormControl, AbstractControl } from '@angular/forms';

6. Create a FormControl property#

Add the following line as a declaration to the PhoneNumComponent class:

import { FormControl, AbstractControl } from '@angular/forms';
export class PhoneNumComponent implements OnInit {
phoneNumber = new FormControl();

7. Validate forms#

We need to create some validation to ensure that the user gives us a valid phone number. We can use a single, synchronous validation rule to ensure the user enters a ten-digit number.

export class PhoneNumComponent implements OnInit {
phoneNumber = new FormControl('', [
(control: AbstractControl) => {
// remove any input that isn't a digit
const numDigits = control.value.replace(/[^\d]+/g, '').length;
// only working with US numbers for now, don't need a country code
if (numDigits === 10) { return null; }
if (numDigits > 10) {
return {
tooLong: { numDigits }
};
} else {
return {
tooShort: { numDigits }
};
}
}
]);

8. Display error messages#

When the inserted phone number is valid, the validator function returns null to show there’s no error.

When there is an error, a validator function returns an object. Now that we’re validating our phone number, let’s update the view to display the new information.

<input [formControl]="phoneNumber" />
<!-- (1) -->
<div *ngIf="phoneNumber.invalid">
<!-- (2) -->
<div *ngIf="(phoneNumber.dirty || phoneNumber.touched)">
<!-- (3) -->
<div *ngIf="phoneNumber.errors.tooLong">
Your phone number has too many digits!
You entered {{ phoneNumber.errors.tooLong.numDigits }}
digits (required: 10)
</div>
<div *ngIf="phoneNumber.errors.tooShort">
Your phone number is too short!
You entered {{ phoneNumber.errors.tooShort.numDigits }}
digits (required: 10)
</div>
</div>
</div>

The next thing we can do is add styling details to CSS classes to add visual cues to the user. But for now, we’ll end the tutorial here.

Common RxJS patterns#

Here’s a brief overview of commonly used RxJS patterns in Angular:

  1. switchMap: Cancels the previous observable and subscribes to a new one, useful for handling async tasks like HTTP requests that should only process the latest value (e.g., live search).

this.searchForm.valueChanges.pipe(
debounceTime(300),
switchMap(query => this.dataService.search(query))
).subscribe(results => this.results = results);
Debounce user input and handle only the latest search query
  1. combineLatest: Combines multiple observables and emits the latest values from each when any observable emits. Ideal for synchronizing multiple data streams, like user and order data.

combineLatest([this.user$, this.orders$]).subscribe(([user, orders]) => {
this.user = user;
this.orders = orders;
});
Synchronize multiple observables and get the latest values from each
  1. forkJoin: Waits for all observables to complete and then emits the results as an array or object. Useful for fetching data from multiple sources.

forkJoin({
user: this.dataService.getUser(),
orders: this.dataService.getOrders()
}).subscribe(result => {
this.user = result.user;
this.orders = result.orders;
});
Wait for all observables to complete and emit their results together
  1. mergeMap: Merges multiple inner observables and processes them concurrently. Best for tasks like concurrent HTTP requests.

this.userService.getUsers().pipe(
mergeMap(user => this.dataService.getUserDetails(user.id))
).subscribe(details => console.log(details));
Fetch and process user details concurrently for each user
  1. retryWhen: Retries an observable after a failure with a delay, ideal for handling transient errors like network issues.

this.dataService.getData().pipe(
retryWhen(errors => errors.pipe(delay(2000), take(3)))
).subscribe(data => this.data = data);
Retry failed data requests with a delay, up to three times

RxJS Observables vs. Promises: A detailed comparison#

Here’s a side-by-side comparison of RxJS Observables vs. Promises to help clarify when to use each:

Feature

Observables

Promises

Execution Model

Lazy, only starts when subscribed

Eager, starts immediately upon creation

Handling Multiple Values

Can emit multiple values over time

Resolves a single value

Cancellation

Can be canceled by unsubscribing

No built-in cancellation (needs extra handling)

Error Handling

Emits errors as part of the observable stream

Caught once and must be handled explicitly

Composition

Can be composed using operators like map, filter, switchMap

Limited chaining, primarily with .then()

Concurrency

Supports concurrency control via operators like mergeMap, concatMap

Does not handle concurrency internally

Performance

Optimized for managing streams of data over time

Efficient for handling one-time async tasks

Use Case

Best for handling streams of data (e.g., user input, real-time updates)

Best for handling one-off async tasks (e.g., API calls)

Key differences#

  • Multiple values: Observables can emit multiple values over time (streams), while Promises resolve once with a single value.

  • Cancellation: Observables can be unsubscribed from, stopping execution, while Promises cannot be canceled once started.

  • Operators: RxJS comes with a rich set of operators to transform, combine, and manage data streams, which makes it far more versatile than Promises.

When to use:#

  • Use observables when handling streams of data, multiple async events, or complex async logic (e.g., user interactions, real-time updates).

  • Use promises for simpler one-time async tasks (e.g., fetching data from an API).

Pros and cons of using RxJS in Angular#

Let's explore the benefits and drawbacks of using RxJS in Angular.

Pros#

  • Efficient async handling: RxJS makes it easy to manage asynchronous operations like API calls, user events, and form inputs.

  • Flexible API: RxJS operators allow for powerful transformations and control over data streams.

  • Performance optimization: RxJS can be optimized with Angular’s change detection and schedulers.

  • Extensive community support: RxJS has a large, active community that continuously improves its features and provides support.

Cons#

  • Steep learning curve: RxJS can be challenging to learn, especially for beginners.

  • Complex debugging: Debugging observables, especially with chained operators, can be tricky.

Tip: Use developer tools like Redux DevTools and logging operators (like tap()) to debug RxJS code effectively.

Wrapping up and next steps#

Congrats on taking your first steps with RxJS in Angular! The RxJS library can help you handle async implementation in a flexible and efficient way. There are still many things to learn about reactive programming and RxJS, such as:

  • Observable streams
  • BehaviorSubject
  • Async Pipe
  • And more

To learn these concepts in more detail, explore our interactive skills path on Educative.

Become an AngularJS Developer

Cover
Become an AngularJS Developer

Angular is a JavaScript framework for building single-page client applications using HTML and TypeScript. If you are not using Angular yet, you're missing out on why Angular can be instrumental in landing a good position in the development industry. This Skill Path will help you learn how to create and deploy scalable applications with Angular. You will also learn automated testing using the Angular framework, state management, and animations in Angular. By the end, you'll have job-ready skills to use Angular in your next project confidently.

143hrs
Beginner
302 Playgrounds
30 Quizzes

By the end, you will be able to build larger, faster, and more reliable applications for your users.

Happy learning!

Continue learning about React#

To deepen your knowledge, explore these related blogs:

Frequently Asked Questions

What is RxJS used for in Angular?

RxJS (Reactive Extensions for JavaScript) in Angular is used for handling asynchronous data streams and events. It enables developers to compose and manage streams of data using operators, making it easier to handle complex tasks like HTTP requests, event handling, and real-time updates in a more declarative and efficient way.

Does RxJS belong to React or Angular?

What is the difference between observable and RxJS?

What is RxJS and NgRx in Angular?

Why do we need RxJS?


Written By:
Erin Schaffer
Join 2.5 million developers at
Explore the catalog

Free Resources