Introducing the HTTP API

Now, before we dive into describing what the Angular framework has given us in terms of   HttpClient service implementation, let's talk about how we can wrap an XmlHttpRequest into an Observable. To do that, we first need to realize that there is a contract that we need to fulfill to consider it a successful wrapping. The contract is made up of the following:

  • Emit any arrived data using observer.next(data)
  • When we don't expect any more data we should call observer.complete()
  • Emit any errors using observer.error(error)

That's it; its pretty simple really. Let's see what a XmlHttpRequest call looks like:

const request = new XMLHttpRequest();

request.onreadystatechange = () => {
if(this.readyState === 4 and this.state === 200) {
// request.responseText
} else {
// error occurred here
}
}

request.open("GET", url);
request.send();

Ok, so we have a typical callback pattern where the onreadystatechange property points to a method that is being invoked once the data arrives. That's all we need to know to wrap the following code, so let's do that:

let stream$ = Rx.Observable.create(observer => {
let request = new XMLHttpRequest();
request.onreadystatechange = () => {
if(this.readyState === 4 && this.state === 200) {
observer.next( request.responseText )
observer.complete();
} else {
observer.error( request.responseText )
}
}
})

That's it, the wrapping is complete; you have now built your own HTTP service. Of course, this isn't much, there are a lot of cases we are not handling, POST, PUT, DELETE, caching, and so on. It was, however, important for you to realize all the heavy lifting the HTTP service in Angular was doing for you. Another important lesson here was how easy it is to take any kind of async API and turn that into an Observable that fits in nicely with the rest of our async concepts. So, let's continue with Angular's implementation of a HTTP service. We will use the HttpClient service from this point.

The HttpClient class provides a powerful API that abstracts all the operations required to handle asynchronous connections through a variety of HTTP methods, handling the responses in an easy and comfortable way. Its implementation was considered with a lot of care to ensure that programmers feel at ease while developing solutions that take advantage of this class to connect to an API or a data resource.

In a nutshell, instances of the HttpClient class (which has been implemented as an Injectable resource and can therefore be used in our class constructors just by injecting it as a dependency provider) expose a connection method named   request()   to perform any type of HTTP connection. The Angular team has created some syntax shortcuts for the most common request operations, such as GET, POST, PUT, and every existing HTTP verb. So, creating an async HTTP request is as easy as this:

let request = new HttpRequest('GET', 'jedis.json');
let myRequestStream:Observable<any> = http.request(request);

Also, all of this can be simplified into a single line of code:

let myRequestStream: Observable<any> = http.get('jedis.json');

As we can see, the HttpClient class connection methods operate by returning an Observable stream. This allows us to subscribe Observers to the stream, which will process the information accordingly once it is returned, as many times as required:

let myRequestStream = http
.get<Jedi[]>('jedis.json')
.subscribe(data => console.log(data));

In the preceding example, we give the get() method a templated type that does the type conversion for us. Let's highlight this bit more:

.get<Jedi[]>('jedis.json')

This very fact saves us from having to deal with a response object directly and performing a map operation to turn our JSON into a list of Jedi objects. All we have to remember is the URL to our resource and specify a type and what you subscribe to is instantly usable for the subscribe of our service.

By doing this, we can respawn the HTTP request as many times as we need, and the rest of our machinery will react accordingly. We can even merge the event stream represented by the HTTP call with other related calls, and compose more complex Observable streams and data threads. The possibilities are endless.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset