17
RxJS Library in Angular
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
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
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 Angular Developer? Your Search ends here.
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'); }
});
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.
17