Features of the HttpClient API
Let's explore how to make REST API calls using the HttpClient service of Angular to the backend of our application.
REST API calls
Now that we have added a HttpClient
service to our application let’s take a look at the API of this class to determine what we can do before we go into the implementation.
Through the HttpClient
class, we can make REST API calls to the backend of our application. These REST API calls are as follows:
These REST calls match the Request methods from the XMLHttpRequest
object that modern browsers support. So, we can see that the HttpClient
class is making use of the browser’s built-in API capabilities.
📝 Note: REST is an architectural structure for creating web services. When a web service follows the REST structure, it is known as a RESTful web service. The name REST comes from its full name, Representational State Transfer. A RESTful web service sends requests to systems so that it can access data from these systems (for example, a web server). For more information on REST, see the Representational State Transfer article on Wikipedia.
So, let’s look at how to make each of these REST calls using the HttpClient
service and understand how they are implemented.
Making a GET request
Making a GET
request using the HttpClient
service is very straightforward. Once we have injected the class into our service, we can write a function that uses the get()
method to call an external API endpoint. Then, we subscribe to the Observable that the get()
method returns. Finally, we listen to the observable, and it returns the response from the API call.
📝 Note: An API endpoint is a reference to a URL that accepts requests. These requests may or may not be REST requests. For a list of great publicly accessible APIs, check out this GitHub repo.
Implementation
That’s the theory. This is how it looks when we implement it. Let’s imagine we are building an Angular application that displays the latest train times, and, as part of this application, we have a page that returns all the current departure times. For this ...