DEV Community

Cover image for RxJS and Angular: Why and how to use
Hunter Johnson for Educative

Posted on • Originally published at educative.io

RxJS and Angular: Why and how to use

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:

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 are 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 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 front-end 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:

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">
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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.

app.module.ts:

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 { }
Enter fullscreen mode Exit fullscreen mode

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
},
Enter fullscreen mode Exit fullscreen mode

5. Create a phone input

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

import { FormControl, AbstractControl } from '@angular/forms';
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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.

phone-num.component.ts part="form-control-prop":

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 }
        };
      }
    }
  ]);
Enter fullscreen mode Exit fullscreen mode

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.

phone-num.component.html part="validation":

 <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>
Enter fullscreen mode Exit fullscreen mode

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.

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

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 on Educative

Start a discussion

What is your favorite JS technology to use? Was this article helpful? Let us know in the comments below!

Top comments (0)