Year-End Discount: 10% OFF 1-year and 20% OFF 2-year subscriptions!

Home/Blog/RxJS and Angular: Why and how to use

RxJS and Angular: Why and how to use

Jun 17, 2021 - 7 min read
Erin Schaffer
editor-page-cover

Reactive Extensions for JavaScript, or RxJS, is a JavaScript library that uses observables for reactive programming. It can be used with other JavaScript libraries and frameworks, and it integrates well into Angular. Today, we will discuss RxJS and Angular, the benefits of using RxJS in Angular, and how to use them together.

We’ll cover:


Build Reactive websites

Build bigger and faster applications with RxJS.

Build Reactive Websites with RxJS: Master Observables and Wrangle

What is RxJS?

The reactive paradigm can be used in many different languages through the use of reactive libraries. These libraries are downloaded APIs that provide functionalities for reactive tools like observers and operators. Reactive Extensions for JavaScript, or RxJS, is a reactive library used to implement reactive programming to deal with async implementation, callbacks, and event-based programs. It can be used in your browser or with Node.js.

RxJS has some core features that help handle async implementation:

  • Observable

    RxJS observables allow you to publish events. Observables have two methods: subscribe and unsubscribe. You execute an observable by subscribing to it. Observables model a stream of events.

  • Observer

    An observer is an object with next(), error(), and complete() methods that is called when there’s an interaction with the observable. They are the objects that subscribe to observables.

  • Subscription

    A subscription to the observable will trigger the observable to execute.

  • Operator

    An operator is a function that allows us to perform certain actions on events executed by observables.

  • Subject

    A subject is the same as an EventEmitter. It is an observable that multicasts information to observers.

  • Scheduler

    A scheduler handles the execution of subscriptions.

The RxJS library is great for handling async tasks. It has a large collection of operators in filtering, error handling, conditional, creation, multicasting, and more. It is supported by JavaScript and TypeScript, and it works well with Angular.

Pros and cons of RxJS

Pros

RxJS is a powerful and popular tool that continues to grow. It has over 2 million dependent repositories on GitHub and over 22 million weekly downloads from NPM. Let’s take a look at some of the reasons why it is so popular:

  • Flexibility: It can be used with other JavaScript libraries and frameworks.

  • Great API: With RxJS, you’re able to simplify your workflow with asynchronous dataflows and save time.

  • Optimized: Many developers have tested and improved it.

  • Extensibility: It is designed to allow new functionalities.

  • Self-sufficient: RxJS doesn’t have any third-party dependencies.

  • Helpful community: Members of the RxJS community help each other solve problems and answer questions.

Cons

Like any other tool, RxJS has a few downsides. Let’s take a look at them:

  • Debugging: Debugging code with observables isn’t always simple.

  • Data immutability: Reactive programming works the best when combined with functional programming.

  • tslib dependency: The only dependency RxJS has is tslib. Details of internal implementation are not always restricted, meaning that you can see some improper usage of access modifiers.

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.

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:


Keep the learning going.

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.

Build Reactive Websites with RxJS: Master Observables and Wrangle


RxJS in Angular

Let’s take a look at how RxJS can work in Angular. We’re going to build a phone number input box.

Let’s get started!

1. Generate a new project

Before we begin, let’s install the Angular CLI using npm install -g @angular/cli. Once finished, we can start working on our application.

Run ng new rx-phone --routing in the directory you want to create the application in.

You will also run ng serve in the root of your project to fire up a server for the phone number input box.

Note: The new command creates a new Angular application. The --routing parameter tells ng to add in an observable-powered routing for the application.

2. Style with CSS

The application we want to build uses Bootsrap’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">
index.html

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>
app.component.html

3. Import reactive forms

Since Reactive forms are not included with Angular, we need to import them at the application level.

Here’s what our code should look like:

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 { }
app.module.ts

4. Generate a new component

  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
},
app-routing.module.ts

5. Create a phone input

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

import { FormControl, AbstractControl } from '@angular/forms';
phone-num.component.ts

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();
phone-num.component.ts

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 }
};
}
}
]);
phone-num.component.ts part="form-control-prop"

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>
phone-num.component.html part="validation"

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


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 and learn how to add styling details to CSS classes in our phone number input box, check out Educative’s curated course Build Reactive Websites with RxJS: Master Observables and Wrangle. In this course, you will learn how to delegate calls and control flows to RxJS using observables.

By the end of the course, you will be able to build bigger, faster, and less-buggy applications for your users.

Happy learning!


Continue learning about React


WRITTEN BYErin Schaffer

Join a community of more than 1.6 million readers. A free, bi-monthly email with a roundup of Educative's top articles and coding tips.