Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Architecting Angular Applications with Redux, RxJS, and NgRx

You're reading from  Architecting Angular Applications with Redux, RxJS, and NgRx

Product type Book
Published in Mar 2018
Publisher Packt
ISBN-13 9781787122406
Pages 364 pages
Edition 1st Edition
Languages
Toc

Table of Contents (12) Chapters close

Preface Quick Look Back at Data Services for Simple Apps 1.21 Gigawatt – Flux Pattern Explained Asynchronous Programming Functional Reactive Programming RxJS Basics Manipulating Streams and Their Values RxJS Advanced Redux NgRx – Reduxing that Angular App NgRx – In Depth Other Books You May Enjoy

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.

You have been reading a chapter from
Architecting Angular Applications with Redux, RxJS, and NgRx
Published in: Mar 2018 Publisher: Packt ISBN-13: 9781787122406
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}