×

iFour Logo

RxJS Library in Angular

Kapil Panchal - November 27, 2020

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
RxJS Library in Angular

What is RxJs?


Reactive Extensions for JavaScriptis a library for reactive programming. RxJS uses observables which will make it easier to compose call back-based code or asynchronous code.

If you are working with Angular, you should at least be familiar with RxJs.The angular framework itself is build using RxJs and around some of the RxJs concepts. We can do much more by using RxJs and observable like better and more readable code and we can even reduce the number of lines of code

Reduce the state of our component by using RxJs Library


The component is a key part of the Angular App structure. Everything in Angular comes around the state of the component and how it will be projected in the UI. On many occasions, we can use streams that will help us to represent volatile pieces of our data inside the view.

RxJs provides an implementation that is an observable type. This implementation is need until the type becomes part of the language and the browser supports it. There are also some utility functions provided by RxJS Library which is helpful for creating and working with observables. These functions can be used for:

 
  • Converting your existing code for async operations into observables
  • Filtering streams
  • Mapping your component value to a different type
  • Composing multiple streams
  • Iterating through the different types

Observable creation functions


There are several functions available in the RxJS library which can be used to create new observables. Those functions can simplify the process of creating new observables from things like events, timers, promises, etc.

Let's take a few examples of creating observable:

 

from a promise

 
import { from } from 'rxjs';

// Observable out of a promise
const records= from(fetch('/api/endpoint'));
// Subscribe to begin listening for async result
data.subscribe({
  next(response) { console.log(response); },
  error(err) { console.error('Error: ' + err); },
  complete() { console.log('Completed'); }
});
				

from a counter

 
import { interval } from 'rxjs';

// Create an Observable that will publish a value on an interval
const counter= interval(1000);
// Subscribe to begin publishing values
const subscription = counter.subscribe(n =>
  console.log(`It's been ${n + 1} seconds since subscribing!`));
				

creates an AJAX request

 
import { ajax } from 'rxjs/ajax';

// To create an AJAX request
  const dataFromApi= ajax('/api/data');
  // Subscribe to create the request
  dataFromApi.subscribe(res => console.log(res.status, res.response));
				

Operators

Operators are function which is built on the observable’s foundation, these operators are used to enable sophisticated manipulation of collections.

For example, we can define operators such as map(), filter(), concat() and flatMap().Operators will take configuration options and they will return a function that takes a source observable. when this return function gets executed, the operator observes the source observable's emitted values, transforms them, and then it will return a new observable of those transformed values.

 

Let’s take one example:

Map operator:

 
import { of } from 'rxjs';
import { map } from 'rxjs/operators';

const numbers= of(1, 2, 3);
const squareValuesofNumber = map((val: number) => val * val);
const squaredNums = squareValuesOfNumbers(numbers);
squaredNums.subscribe(x => console.log(x));

// Logs
// 1
// 4
// 9
				

We can also use some pipes to link those operators together. By using pipes, you can combine multiple functions into a single function. The function which you want to combine can be used as pipe's arguments and it will return a new function that, when gets executed, runs the composed functions in sequence.

A set of operators applied to an observable is called a recipe which is a set of instructions for producing the values you want. The recipe will not do anything by itself, you will have to call subscribe () to produce a result from it.

Let’s take an example:

Observable.pipe function

import { of, pipe } from 'rxjs';
import { filter, map } from 'rxjs/operators';

const numbers = of(1, 2, 3, 4, 5);
// function that accepts an Observable.
const squareOfOddVals = pipe(
  filter((n: number) => n % 2 !== 0),
  map(n => n * n)
);
// Observable that will run the filter and map functions
const squareOfOdd = squareOfOddVals(numbers);
// Subscribe to run the combined functions
squareOfOdd.subscribe(x => console.log(x));
				

We can also do the same thing in shorter form because pipe () function is also a method in the RxJs observable:

 
import { of } from 'rxjs';
import { filter, map } from 'rxjs/operators';

const squareOfOdd = of(1, 2, 3, 4, 5)
  .pipe(
    filter(n => n % 2 !== 0),
    map(n => n * n)
  );
// Subscribe to get values
squareOfOdd.subscribe(x => console.log(x));				
				

Some Common operators

There are many operators available, but only a few come to a handful in regular use.

Looking to hire dedicated Angular Developer ?
Your Search ends here.

 

Error Handling

RxJs provides the catchError operator which will help you to handle known errors in the observable recipe.

For example, let's assume that you have an observable which will be going to make an API request and map to the response from the server. And if there is a case when the server returns an error or the value doesn't exist, you can catch this error and supply any default value and your steam will not stop and will continue with that default value.

Let’s take an example:

CatchError Operator:

 
import { of } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { map, catchError } from 'rxjs/operators';

// Return "response" from the API. If an error happens,
// return an empty array.
const dataFromApi = ajax('/api/data').pipe(
  map((res: any) => {
    if (!res.response) {
      throw new Error('Value expected!');
    }
    return res.response;
  }),
  catchError(err => of([]))
);
dataFromApi.subscribe({
  next(x) { console.log('data: ', x); },
  error(err) { console.log('errors already caught... will not run'); }
});
				

Conclusion


RxJs is a powerful library, there is no doubt why angular is built around it. We can use RxJS to make our code more readable, easier, and better. You can do much more with RxJs library than the example shown in this article.

RxJS Library in Angular Table of Content 1. What is RxJs? 2. Reduce the state of our component by using RxJs Library 3. Observable creation functions 3.1 from a promise 3.2 from a counter 3.3 creates an AJAX request 3.4 Operators 3.5 Observable.pipe function 3.6 Some Common operators 3.7 Error Handling 4. Conclusion What is RxJs? Reactive Extensions for JavaScriptis a library for reactive programming. RxJS uses observables which will make it easier to compose call back-based code or asynchronous code. If you are working with Angular, you should at least be familiar with RxJs.The angular framework itself is build using RxJs and around some of the RxJs concepts. We can do much more by using RxJs and observable like better and more readable code and we can even reduce the number of lines of code Reduce the state of our component by using RxJs Library The component is a key part of the Angular App structure. Everything in Angular comes around the state of the component and how it will be projected in the UI. On many occasions, we can use streams that will help us to represent volatile pieces of our data inside the view. RxJs provides an implementation that is an observable type. This implementation is need until the type becomes part of the language and the browser supports it. There are also some utility functions provided by RxJS Library which is helpful for creating and working with observables. These functions can be used for:   Converting your existing code for async operations into observables Filtering streams Mapping your component value to a different type Composing multiple streams Iterating through the different types Observable creation functions There are several functions available in the RxJS library which can be used to create new observables. Those functions can simplify the process of creating new observables from things like events, timers, promises, etc. Let's take a few examples of creating observable:   from a promise   import { from } from 'rxjs'; // Observable out of a promise const records= from(fetch('/api/endpoint')); // Subscribe to begin listening for async result data.subscribe({ next(response) { console.log(response); }, error(err) { console.error('Error: ' + err); }, complete() { console.log('Completed'); } }); from a counter   import { interval } from 'rxjs'; // Create an Observable that will publish a value on an interval const counter= interval(1000); // Subscribe to begin publishing values const subscription = counter.subscribe(n => console.log(`It's been ${n + 1} seconds since subscribing!`)); creates an AJAX request   import { ajax } from 'rxjs/ajax'; // To create an AJAX request const dataFromApi= ajax('/api/data'); // Subscribe to create the request dataFromApi.subscribe(res => console.log(res.status, res.response)); Operators Operators are function which is built on the observable’s foundation, these operators are used to enable sophisticated manipulation of collections. For example, we can define operators such as map(), filter(), concat() and flatMap().Operators will take configuration options and they will return a function that takes a source observable. when this return function gets executed, the operator observes the source observable's emitted values, transforms them, and then it will return a new observable of those transformed values. Read More: Understanding @output And Eventemitter In Angular   Let’s take one example: Map operator:   import { of } from 'rxjs'; import { map } from 'rxjs/operators'; const numbers= of(1, 2, 3); const squareValuesofNumber = map((val: number) => val * val); const squaredNums = squareValuesOfNumbers(numbers); squaredNums.subscribe(x => console.log(x)); // Logs // 1 // 4 // 9 We can also use some pipes to link those operators together. By using pipes, you can combine multiple functions into a single function. The function which you want to combine can be used as pipe's arguments and it will return a new function that, when gets executed, runs the composed functions in sequence. A set of operators applied to an observable is called a recipe which is a set of instructions for producing the values you want. The recipe will not do anything by itself, you will have to call subscribe () to produce a result from it. Let’s take an example: Observable.pipe function import { of, pipe } from 'rxjs'; import { filter, map } from 'rxjs/operators'; const numbers = of(1, 2, 3, 4, 5); // function that accepts an Observable. const squareOfOddVals = pipe( filter((n: number) => n % 2 !== 0), map(n => n * n) ); // Observable that will run the filter and map functions const squareOfOdd = squareOfOddVals(numbers); // Subscribe to run the combined functions squareOfOdd.subscribe(x => console.log(x)); We can also do the same thing in shorter form because pipe () function is also a method in the RxJs observable:   import { of } from 'rxjs'; import { filter, map } from 'rxjs/operators'; const squareOfOdd = of(1, 2, 3, 4, 5) .pipe( filter(n => n % 2 !== 0), map(n => n * n) ); // Subscribe to get values squareOfOdd.subscribe(x => console.log(x)); Some Common operators There are many operators available, but only a few come to a handful in regular use. Looking to hire dedicated Angular Developer ? Your Search ends here. See here   Error Handling RxJs provides the catchError operator which will help you to handle known errors in the observable recipe. For example, let's assume that you have an observable which will be going to make an API request and map to the response from the server. And if there is a case when the server returns an error or the value doesn't exist, you can catch this error and supply any default value and your steam will not stop and will continue with that default value. Let’s take an example: CatchError Operator:   import { of } from 'rxjs'; import { ajax } from 'rxjs/ajax'; import { map, catchError } from 'rxjs/operators'; // Return "response" from the API. If an error happens, // return an empty array. const dataFromApi = ajax('/api/data').pipe( map((res: any) => { if (!res.response) { throw new Error('Value expected!'); } return res.response; }), catchError(err => of([])) ); dataFromApi.subscribe({ next(x) { console.log('data: ', x); }, error(err) { console.log('errors already caught... will not run'); } }); Conclusion RxJs is a powerful library, there is no doubt why angular is built around it. We can use RxJS to make our code more readable, easier, and better. You can do much more with RxJs library than the example shown in this article.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Power Apps vs Power Automate: When to Use What?
Power Apps vs Power Automate: When to Use What?

I often see people asking questions like “Is Power App the same as Power Automate?”. “Are they interchangeable or have their own purpose?”. We first need to clear up this confusion...

Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula
Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula

We always hear about how important it is to be competitive and stand out in the market. But as an entrepreneur, how would you truly set your business apart? Is there any way to do...

React 18 Vs React 19: Key Differences To Know For 2024
React 18 Vs React 19: Key Differences To Know For 2024

Ever wondered how a simple technology can spark a revolution in the IT business? Just look at React.js - a leading Front-end JS library released in 2013, has made it possible. Praised for its seamless features, React.js has altered the way of bespoke app development with its latest versions released periodically. React.js is known for building interactive user interfaces and has been evolving rapidly to meet the demands of modern web development. Thus, businesses lean to hire dedicated React.js developers for their projects. React.js 19 is the latest version released and people are loving its amazing features impelling them for its adoption.