What is RxJS in Angular?

RxJS (Reactive Extensions for JavaScript) is a library that supports reactive programming using observables in Angular and other JavaScript applications. It is a key part of Angular's ecosystem and is widely used for handling asynchronous operations, managing event streams, and handling data flow.

Utilization in Angular

In Angular, RxJS is mainly used for the following:

Event handling

Angular uses RxJS observables to handle events from the DOM, such as mouse clicks and keyboard presses. This makes it easier to handle events consistently and to react to events more asynchronously.

At its core, RxJS introduces the concept of observables, an abstraction representing a sequence of values over time. Observables can emit data (including events) and can be subscribed to by various application parts to react to those emissions. RxJS provides operators that allow you to transform, filter, combine, and manage these data sequences in a declarative and composable way.

Key concepts

  • Observables: Observables are sources of data or streams of values that can be observed over time. They can emit values, errors, or a completion signal.

  • Operators: RxJS provides a wide range of operators (e.g., map, filter, merge, combineLatest, etc.) that allow you to transform, filter, combine, or perform various operations on observables, enabling you to build complex data flows with ease.

  • Subscriptions: Subscriptions listen to and react to the data emitted by observables. When you subscribe to an observable, you can receive the emitted values, handle errors, and manage the completion of the observables.

  • Subjects: Subjects act as both observables and observers. They allow you to multicast values to multiple subscribers, making them useful for broadcasting events or sharing data between components.

Here is an example of subscribing to an observable in Angular:

import { Observable } from 'rxjs';
const myObservable = new Observable<number>((observer) => {
observer.next(1);
observer.next(2);
observer.next(3);
observer.complete();
});
myObservable.subscribe(
(value) => console.log('Next:', value),
(error) => console.error('Error:', error),
() => console.log('Complete')
);

Code explanation

  • Lines 1–8: This code imports Observable and creates a simple Observable that emits three values (1, 2, and 3) and then completes.

  • Lines 10–14: The subscribe() method sends the emitted values in the specified order. This method takes three arguments. The first argument to the subscribe() method is a function that will be called to display the emitted values by Observable. The value that is emitted will be the response from the HTTP request. The second argument to the subscribe() method is a function that will be called when the observable emits errors. The third argument to the subscribe() method is a function that will be called when the observable completes. The observable will complete when the HTTP request is complete.

Data binding

Angular uses RxJS observables to bind data from the model to the view. This makes it easier to update the view when the model changes, and to prevent the view from becoming out of sync with the model.

HTTP requests

Angular uses RxJS observables to make HTTP requests. This makes it easier to handle the asynchronous nature of HTTP requests and to react to the results of the requests in a more asynchronous way. Let's look at an example:

.book-grid {
    display: grid;
    grid-template-columns: repeat(4, 150px) ;
    gap:80px;
    justify-content:center;
    column-rule: 10px solid #302d18;
    padding-bottom: 30px;
}

.book{
    position: relative;
    width: 200px;
    /* height: 30px; */
    border-radius: 10px;
    box-shadow: 10px 10px 43px -18px rgba(0, 0, 0, 0.75);
    transform-style: preserve-3d; 
    -webkit-transition: transform 0.6s ease-in-out; /* Safari and Chrome */
    transition: transform  0.6s ease-in-out;
}

img {
    width: 200px;
    height: 250px;
    object-fit:fill;
    border-radius: 10px;
}  
.book-author {
    height: 30px;
    padding: 14px;
    margin: 0px;
    color: saddlebrown;}

HTTP request example

Code explanation

The app.component.html file in the above coding example displays the book results. In the app.component.ts file of the coding example:

  • Lines 1–19: We have imported the packages and defined the class.

  • Line 25: The constructor() method takes a single parameter, private http: HttpClient, which is an instance of the HttpClient class. The HttpClient class is used to make HTTP requests.

  • Lines 22–50: The ngOnInit() method makes an HTTP request to the https://gutendex.com/books?search='+'room' endpoint, catches error using RxJS operator and stores the results in the retreivedBooks variable. The get() method on the HttpClient class takes the URL of the endpoint as its argument and returns an observable. The observable will emit the results of the request when the request is complete. The subscribe() method sends the values or any errors emitted by the observable.

Copyright ©2024 Educative, Inc. All rights reserved