RxJS is a first-class citizen inAngular. It is part of theAngular ecosystem and is used in many features to handle asynchronous operations. Primarily, this includes the following:
- HTTP client module
- Router module
- Reactive forms
- Event emitter
- Async pipe
We will discuss each of the following concepts in the subsequent subsections.
Note
We recommend taking a quick look athttps://angular.io/docs. Here, you can find further details about the features mentioned earlier.
The HTTP client module
You might befamiliar with the HTTP client API provided by Angular in order to communicate with your server over the HTTP protocol. TheHttpClient service is based on observables to manage all transactions. This means that the result of calling the API methods (such asGET,PATCH,POST, orPUT) is an observable.
In the following code snippet, we have an example of an Angular service that injects theHttpClient service and fetches data from the server using theHttpClient.get() method:
Import { Injectable } from '@angular/core';import { HttpClient } from '@angular/common/http';import { Observable} from 'rxjs';import { environment } from '@env/environment';const BASE_PATH = environment.basePath;@Injectable()export class RecipesService {constructor(private http: HttpClient) { }getRecipes(): Observable<Recipe[]> {return this.http.get<Recipe[]>(`${BASE_PATH}/recipes/search/all`);}The following is the content of theenvironment.ts file where we define thebasePath property of our backend:
export const environment = { basePath: '/app/rest', production: false};ThegetRecipes() method or, to be more accurate, the call tothis.http.get<Recipe>(`${BASE_PATH}/recipes/search`) returns an observable that you should subscribe to in order to issue theGET request to the server. Please note that this is an example of an HTTP transaction, and it is the same for all of the other HTTP methods available in the API (such asPOST,PUT, andPATCH)
For those familiar with promise-based HTTP APIs, you might be wondering, in this case, what the advantages of using observables are.
Well, there are a lotof advantages but the most important ones are listed as follows:
- Observables are cancellable, so you can cancel the HTTP request whenever you want by calling the unsubscribe method.
- Also, you can retry HTTP requests when an error occurs or an exception is thrown.
- The server's response cannot be mutated by observables, although this can be the case when chaining
then() to promises.
The router module
The router module, which is available in the@angular/router package, uses observables in router events and activated routes.
Router events
The router exposes eventsas observables. The router events allow you to intercept the navigation life cycle. The following list shows the sequence of router events:
To intercept all the events that the router goes through, first, you should inject theRouter service, which provides navigation and URL manipulation capabilities. Then, subscribe to theevents observable available in theRouter object, and filter the events of theRouterEvent type using therxjs filter operator.
This is an example of an Angular service that injects theRouter object in the constructor, subscribes to the router events, and just traces the event ID and path in the console. However, note that you can also introduce pretty much any specific behavior:
import { Injectable } from '@angular/core';import { Router, RouterEvent } from '@angular/router';import { filter } from 'rxjs/operators';@Injectable()export class CustomRouteService { constructor(public router: Router) { this.router.events.pipe( filter(event => event instanceof RouterEvent) ).subscribe((event: RouterEvent) => { console.log(`The current event is : ${event.id} | event.url`); }); }}You can filter any specific event by putting the target type. The following code example only filters theNavigationStart event and traces the event ID and path inside the console. However, you can also introduce pretty much any specific behavior:
import { Injectable } from '@angular/core';import { NavigationStart, Router } from '@angular/router';import { filter } from 'rxjs/operators';@Injectable()export class CustomRouteService { constructor(public router: Router) { this.router.events.pipe( filter(event => event instanceof NavigationStart) ).subscribe((event: NavigationStart) => { console.log(`The current event is : ${event.id} | event.url`); }); } }The majority of Angular applications have a routing mechanism. The router events change frequently over time, and it makes sense to listen to changes to execute the side effects. That's why observables are a flexible way in which to handle those streams.
The activated route
TheActivatedRoute class is a router service that you can inject into your components to retrieve information about a route's path and parameters. Many properties are based on observables. Here, you will find the contract (refers to the exposed methods and properties) of the activated route class:
class ActivatedRoute { snapshot: ActivatedRouteSnapshot url: Observable<UrlSegment[]> params: Observable<Params> queryParams: Observable<Params> fragment: Observable<string | null> data: Observable<Data> outlet: string component: Type<any> | string | null routeConfig: Route | null root: ActivatedRoute parent: ActivatedRoute | null firstChild: ActivatedRoute | null children: ActivatedRoute[] pathFromRoot: ActivatedRoute[] paramMap: Observable<ParamMap> queryParamMap: Observable<ParamMap> toString(): string}As you might havegathered,url,params,queryParams,fragment,data,paramMap, andqueryParamMap are represented as observables. Refer to the following list:
url: This is an observable that holds the URL of the active route.params: This is an observable that holds the parameters of the active route.queryParams: This is an observable that holds the query parameters shared by all of the routes.fragment: This is an observable that holds the URL fragment shared by all the routes.data: This is an observable that holds the static and resolved data of the active route.paramMap: This is an observable that holds a map of the required parameters and the optional parameters of the active route.queryParamMap: This is an observable that holds a map of the query parameters available to all the routes.
All these parameters might changeover time. Routes might share parameters, the parameters might have dynamic values, and it makes perfect sense to listen to those changes to register side effects or update the list of parameters.
Here's an example of an Angular component that injects theActivatedRoute class in the constructor and subscribes, in thengOnInit() method, to the following:
- The
url property ofactivatedRoute, logging the URL in the console - The
queryParams property ofactivatedRoute in order to retrieve the parametercriteria and store it in a local property, namedcriteria:import { Component, OnInit } from '@angular/core';import { ActivatedRoute } from '@angular/router';@Component({ selector: 'app-recipes', templateUrl: './recipes.component.html'})export class RecipesComponent implements OnInit { criteria: any; constructor(private activatedRoute: ActivatedRoute) { } ngOnInit() { this.activatedRoute.url .subscribe(url => console.log('The URL changed to: ' + url)); this.activatedRoute.queryParams.subscribe(params => { this.processCriteria(params.criteria); }); } processCriteria(criteria: any) { this.criteria = criteria; }}
Reactive forms
Reactive formsavailable under the@angular/forms package are based on observables to track form control changes. Here's the contract of theFormControl class in Angular:
class FormControl extends AbstractControl { //other properties here valueChanges: Observable<any> statusChanges: Observable<any>}TheFormControl properties ofvalueChanges andstatusChanges are represented as observables that trigger change events. Subscribing to aFormControl value change is a way of triggering application logic within thecomponent class.
Here's an example of an Angular component that subscribes to thevalueChanges of aFormControl property calledratingand simply traces the value throughconsole.log(value). In this way, each time, you will get the changed value as an output:
import { Component, OnInit } from '@angular/core';import { FormGroup } from '@angular/forms';@Component({ selector: 'app-recipes', templateUrl: './recipes.component.html'})export class MyComponent implements OnInit { form!: FormGroup; ngOnInit() { const ratingControl = this.form.get('rating'); ratingControl?.valueChanges.subscribe( (value) => { console.log(value); } ); }}The event emitter
The event emitter, which ispart of the@angular/core package, is used to emit data from a child component to a parent component through the@Output() decorator. TheEventEmitter class extends the RxJS subject and registers handlers for events emitted by this instance:
class EventEmitter<T> extends Subject { constructor(isAsync?: boolean): EventEmitter<T> emit(value?: T): void subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription}This is what happens under the hood when you create an event emitter and emit a value.
The following is an example of an Angular component that emits the updated value of a recipe rating:
import { Component, Output } from '@angular/core';import { EventEmitter } from 'events'; @Component({ selector: 'app-recipes', templateUrl: './recipes.component.html' })export class RecipesComponent { constructor() {} @Output() updateRating = new EventEmitter(); updateRecipe(value: string) { this.updateRating.emit(value); }}The async pipe
Here,AsyncPipe automatically subscribes to an observable when used in a component's template andemits the latest value each time. This avoids subscribing logic in the component and helps with binding and updating your asynchronous streams data in the template. In this example, we are using an async pipe insidengIf. Thisdiv tag will only be rendered when thedata$ variable emits something:
<div *ngIf="data$ | async"></div>
We will cover the advantages and usage of async pipes inChapter 4,Fetching Data as Streams.
Note
In the previous code snippets, the subscription to the observables was done explicitly for demonstration purposes. In a real-world example, we should include the unsubscription logic if we use an explicit subscription. We will shed light on this inChapter 4,Fetching Data as Streams.
Now that we have learned about the advantages of using RxJS in Angular and how it makes dealing with some concepts smoother, let's explore the marble diagram, which is very handy for understanding and visualizing the observable execution.