×

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 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.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

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
How Spatial Data Analysis Improves Healthcare
How Spatial Data Analysis Improves Healthcare

Do you know when geospatial analysis took traction in healthcare? It was when John Snow, a London-based physician, used it to analyze the spread of cholera, which ultimately proved...

4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical
4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical

One interesting aspect you truly love about Power BI, as a CTO, is how it lets you step back and see the bigger picture of your business. Isn’t it? Without getting bogged down in minute...

Power Apps Integration Challenges: Expert Insights & Solutions
Power Apps Integration Challenges: Expert Insights & Solutions

Power Apps Integration Challenges: Insights from 11 Experts Microsoft Power Apps has caught great hype in recent days. Why? because it helps you build apps 50% faster, saves 250+...