- Architecting Angular Applications with Redux,RxJS,and NgRx
- Christoffer Noring
- 793字
- 2021-08-27 19:56:17
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.