June 17, 2021-7 minutes to read
Erin Schaffer
Reactive Extensions for JavaScript, or RxJS, is a JavaScript library that uses an observer for Reactive programming. It works with other JavaScript libraries and frameworks, and integrates well with Angular. Today, we’ll talk about RxJS and Angular, the benefits of using RxJS in Angular, and how to use them together.
We will introduce.
- What is RxJS?
- Advantages and disadvantages of RxJS
- What is Angular?
- Presents the RxJS
- Summary and next steps
What is RxJS?
By using the reaction library, the reaction paradigm can be used in many different languages. These libraries are downloaded apis that provide functionality for reactive tools such as observers and operators. Reactive Extensions for JavaScript, or RxJS, is a Reactive library for Reactive programming to handle asynchronous execution, callbacks, and event-based programs. It can be used in your browser or with Node.js.
RxJS has some core features that help handle asynchronous implementations.
-
That can be viewed
RxJS’s observer allows you to publish events. Observers have two methods: subscribe and unsubscribe. You execute an observable variable by subscribing to it. The observer models a flow of events.
-
The observer
An observer is an object with next(),error(), and complete() methods that are called when an interaction with an observer occurs. These are the objects that subscribe to the observer.
-
To subscribe to
Subscription to the observer triggers execution of the observer.
-
The operator
The operator is a function that allows us to perform certain operations on the events performed by the observer.
-
The main body
The subject is the same as EventEmitter. It’s an observer, and it sends messages to a group of observers.
-
The scheduler
A scheduler handles the execution of the subscription.
The RxJS library is great for handling asynchronous tasks. It has a large number of operators in filtering, error handling, conditioning, creation, multicast, and so on. It is supported by JavaScript and TypeScript and works well with Angular.
Advantages and disadvantages of RxJS
advantages
RxJS is a powerful and popular tool that continues to grow. It has over 2 million dependent libraries on GitHub and over 22 million downloads per week on NPM. Let’s look at some of the reasons why it’s so popular.
-
Flexibility. It can be used with other JavaScript libraries and frameworks.
-
Great API. With RxJS, you can simplify your workflow and save time with asynchronous data flows.
-
The optimization. Many developers have tested and improved on it.
-
Scalability. It is designed to allow new functionality.
-
Be self-sufficient. RxJS does not have any third party dependencies.
-
Helpful communities. Members of the RxJS community help each other solve problems and answer questions.
disadvantages
Like any other tool, RxJS has some drawbacks. Let’s take a look at them.
-
Debugging. Debugging code with observable variables is not always easy.
-
Data cannot be modified. Reactive programming works best when combined with functional programming.
-
Tslib dependency. The only dependency of RxJS is tSLIb. The details of the internal implementation are not always limited, which means you can see some inappropriate use of access modifiers.
What is Angular?
Angular is a Web application framework 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.
-
component
Angular components are the core UI building blocks of Angular applications. Every component has it.
- An HTML template that declares what is displayed on a page
- A TypeScript class that defines its behavior
- A CSS selector that defines how to use this component in a template
-
The template
Templates are used by components. They declare how components are rendered on the page. Directives allow you to add additional functionality to your templates. Directives can do a lot of things, such as allowing you to modify the DOM structure. The most popular are ngfor and ngif.
-
Dependency injection
Dependency injection is not required when using Angular, but it is called a best practice. It allows you to declare your class’s dependencies and let Angular handle the instantiation.
-
library
Libraries extend Angular’s base functionality and allow you to do many different things. There are many Angular libraries you can use, for example.
- Angular Router
- Angular HttpClient
- Presents the form
- Angular PWA
- And so on.
Presents the RxJS
Let’s see how RxJS works in Angular. We will create a phone number entry box.
Let’s get started!
1. Create a new project
Before we begin, let’s install the Angular CLI using NPM install -g @angular/cli. Once that’s done, we can start developing our application.
Run ng new rx-phone –routing in the directory where you want to create the application.
You will also run ng Serve in the root directory of your project to start a server for the phone number entry box.
Note: The new command creates a new Angular application. The –routing parameter tells ng to add an observable route to the application.
2. Use CSS styles
The application we’re going to build uses Bootsrap’s CSS for visual effects. We’ll open index.html first. Then, let’s bring CSS in and add the following tags to the file.
<! -- Bootstrap (loaded from local server) --> <link rel="stylesheet" href="http://localhost:3000/assets/bootstrap.min.css">Copy the code
index.html
You’ll see some placeholder HTML in app.component.html. Delete it and add this in its place.
<div class="container">
<router-outlet></router-outlet>
</div>
Copy the code
app.component.html
3. Import the reaction form
Because Reactive forms are not included in 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 { }
Copy the code
app.module.ts
4. Generate a new component
- run
ng generate component phone-num
To add a declaration for the routing module. - with
ng serve
Start the Angular server. - Add a route to the new component
app-routing.module.ts
。
{
path: 'phone',
component: PhoneNumComponent
},
Copy the code
app-routing.module.ts
5. Create a phone input
Open unlocked num.component.ts and import FormControl and AbstractControl.
import { FormControl, AbstractControl } from '@angular/forms';
Copy the code
phone-num.component.ts
6. Create oneFormControl
attribute
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();
Copy the code
phone-num.component.ts
7. Validate the form
We need to create some validation to make sure the user gives us a valid phone number. We can use a single, synchronous authentication rule to ensure that 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 }
};
}
}
]);
Copy the code
phone-num.component.ts part=”form-control-prop”
8. An error message is displayed
When the inserted phone number is valid, the validator function returns null, indicating no error.
_ When there is an _ error, the validator function returns an object. Now that we are 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>Copy the code
phone-num.component.html part=”validation”
The next thing we can do is add styling details to the CSS class to add visual cues to the user. This is where we’ll end the tutorial.
Summary and next steps
Congratulations on taking your first RxJS step in Angular! The RxJS library can help you handle asynchronous implementations in a flexible and efficient manner. There’s still a lot to learn about reactive programming and RxJS, for example.
- Observed stream
- The BehaviorSubject is BehaviorSubject
- Asynchronous pipeline
- And more
To learn these concepts, and to learn how to add styling details to our CSS classes in our phone number input box, check out Educative’s Mastermind course on Building Reactive Websites with RxJS: Mastering Observable Data and Wrangle. In this course, you will learn how to delegate calls and control flows to RxJS using observables.
By the end of this course, you will be able to build bigger, faster, and error-less applications for your users.
Happy study!
Learn more about React
- Five best practices for React developers
- Start using React and TypeScript
- The React tutorial. How to build Instagram’s user interface with React
By Erin Schaffer
Join a community of 270,000 monthly readers. Free bi-monthly email that includes Educative’s top articles and a roundup of coding tips.
Spend half the time learning in-demand technical skills
Copyright © 2021 Educative, Inc. All rights reserved.