Book Image

Architecting Angular Applications with Redux, RxJS, and NgRx

Book Image

Architecting Angular Applications with Redux, RxJS, and NgRx

Overview of this book

Managing the state of large-scale web applications is a highly challenging task with the need to align different components, backends, and web workers harmoniously. When it comes to Angular, you can use NgRx, which combines the simplicity of Redux with the reactive programming power of RxJS to build your application architecture, making your code elegant and easy to reason about, debug, and test. In this book, we start by looking at the different ways of architecting Angular applications and some of the patterns that are involved in it. This will be followed by a discussion on one-way data flow, the Flux pattern, and the origin of Redux. The book introduces you to declarative programming or, more precisely, functional programming and talks about its advantages. We then move on to the reactive programming paradigm. Reactive programming is a concept heavily used in Angular and is at the core of NgRx. Later, we look at RxJS, as a library and master it. We thoroughly describe how Redux works and how to implement it from scratch. The two last chapters of the book cover everything NgRx has to offer in terms of core functionality and supporting libraries, including how to build a micro implementation of NgRx. This book will empower you to not only use Redux and NgRx to the fullest, but also feel confident in building your own version, should you need it.
Table of Contents (12 chapters)

Fetching and persisting data with HTTP – introducing services with Observables

So far, we have gone through a data flow where the component is our view to the outside world, but also the controller. The component uses a service to get the data, but also to persist it. The data, however, has up until this point lived in the service and that's not a very likely place for it to reside. Almost certainly, that data should be fetched and persisted to an endpoint. That endpoint is an exposed URL to a backend system published somewhere on the internet. We can use HTTP to reach said endpoint. Angular has created a wrapper on top of the vanilla way of fetching data through HTTP. The wrapper is a class that wraps the functionality of an object called XmlHttpRequest. The Angular wrapper class is called the HttpClient service.

Fetching data with the HTTP service

There is more than one way to communicate over HTTP. One way is using the XmlHttpRequest object, but that is a quite cumbersome and low-level way of doing it. Another way is to use the new fetch API, which you can read more about here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API.

Angular has its own abstraction, the HTTP service, which can be found in the HTTPModule. To use it, simply import the HttpModule:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
imports: [HttpClientModule]
})

Then, inject the HttpClient service where you want to use it, like so:

import { HttpClient } from '@angular/common/http';

@Component({
selector: 'consumer',
template: ``
})
export class ConsumerComponent {
constructor(private http:HttpClient) {}
}

At this point, we are ready to use it. Let's see a quick overview of what methods this HTTP service has:

  • get('url', <optional options param>) fetches the data for us
  • post('url', payload,<optional options param>) creates a resource
  • put('url', payload,<optional options param>) updates a resource
  • delete('url',<optional options param>) removes a resource
  • request is a raw request where you can configure exactly what call you want to make, what headers you want to add, and so on

When we use http.get() we get a construct back called an Observable. An Observable is just like the Promise, an asynchronous concept that enables us to attach callbacks to when the data arrives some time in the future, as well as attaching callbacks to an error when an error occurs. The RxJS implementation of the Observable comes packed with a number of operators that help us transform the data and interact with other Observables. One such operator is called toPromise() and enables us to convert an Observable to a Promise. With this, we can make HTTP calls in two different ways, or flavors. The first way is where we use the toPromise() operator and convert our Observable to a Promise, and the other is using our Observable and dealing with the data that way.

A typical call comes in two different flavors:

  • Using promises
// converting an Observable to a Promise using toPromise()
http
.get('url')
.toPromise()
.then(x => x.data)
.then(data => console.log('our data'))
.catch(error => console.error('some error happened', error));

This version feels familiar. If you need to brush up on Promises, have a look at the following link before continuing: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise. We recognize the .then() method as the method that is called when the data arrives and the .catch() method that is called when something goes wrong with our request. This is what we expect when, dealing with promises.

  • Using RxJS
// calling http.get() and gets an Observable back
http
.get('url')
.map( x => x.data )
.subscribe( data => console.log('our data', data))
.catch( error => console.error('some error happened', error))

The second version looks different. Here, we are using the .map() method in much the same way as we used the .then() method. This statement needs some explanation. Let's have a look at the promise flavor code one more time and highlight what we are saying:

http
.get('url')
.toPromise()
.then(x => x.data)
.then(data => console.log('our data'))
.catch(error => console.error('some error happened', error));

The highlighted portion is the method that is called when the data first arrives from the service. What we do inside of this call is to create a projection of the data, like so:

.then(x => x.data)

The subsequent call to then() just deals with printing the data to the console:

.then(data => console.log('our data'))

Let's now have a look at how the RxJS version differs by highlighting the projection part and the part where we print out our result:

http
.get('url')
.map( x => x.data )
.subscribe( data => console.log('our data', data) )
.catch( error => console.error('some error happened', error) )

The first line of our highlighted portion of the code indicates our projection:

.map( x => x.data )

The call to subscribe is where we print our data, like so:

.subscribe( data => console.log('our data', data) )

When we use http.get(), we get a construct back called an Observable. An Observable is just like the Promise, an asynchronous concept that enables us to attach callbacks to when the data arrives some time in the future, as well as attaching callbacks to when an error happens.

The Observable is part of a library called RxJS and this is what is powering the HttpClient service. It is a powerful library meant for more than just a simple request/response pattern. We will spend future chapters exploring the RxJS library further and discover what a powerful paradigm the Observable really is, what other important concepts it brings, and the fact that it isn't really only about working with HTTP anymore, but all async concepts.