HTTP requests allow us to request resources that our application can make use of. In the context of this article, this will generally mean requesting data from some API over the Internet, or loading data from a JSON file over the local network. These are HTTP requests that we are going to be launching manually through our code.
However, HTTP requests are also used to load other resources in our applications like images or CSS files. If you open up the debugging window, go to the ‘Network’ tab, and reload any web page, you will probably see a bunch of HTTP requests that are launched to load various resources.
In effect, an HTTP request is where the browser is given a particular URL and asked to load the resource that lives at that URL (or, send data to that URL).
The HttpClient and HttpClientModule
Many of the resources in our application are automatically loaded over the network (e.g. images, JavaScript files, CSS files), but often we will need to manually launch an HTTP request from our code to grab data. Generally, we would do this when we need to load some data from an API or a JSON file.
In order to make HTTP requests in an Ionic/Angular environment, we need to make use of the HttpClient
and HttpClientModule
that Angular provides. This just happens to be the way that Angular deals with HTTP requests and the HttpClient
is provided to make it easier for us to launch HTTP requests in an Angular environment. In different environments, the way in which you launch an HTTP request will differ.
First, we must add the HttpClientModule
to the root module of our application:
Import the
HttpClientModule
in src/app/app.module.ts:
import { HttpClientModule } from '@angular/common/http';
Add the
HttpClientModule
to the imports array in src/app/app.module.ts:
imports: [
BrowserModule,
HttpClientModule,
IonicModule.forRoot(),
AppRoutingModule
],
By adding the HttpClientModule
to our imports, we are making the functionality that is necessary to make HTTP requests available throughout the application.
With the HttpClientModule
set up, we then need to inject the HttpClient
into any class where we want to launch an HTTP request.
Import the
HttpClient
into any files that contain classes where you want to make HTTP requests:
import { HttpClient } from '@angular/common/http';
Inject the
HttpClient
into the constructor of any class where you want to make HTTP requests:
constructor(private http: HttpClient) {
}
The example above injects the HttpClient
as http
which will allow HTTP requests to be launched from anywhere within that class like this:
this.http.get('https://someapi.com/posts').subscribe((response) => {
console.log(response);
});
The Role of Observables in HTTP Requests
When dealing with the HttpClient
it is important to have a basic understanding of observables. In the code above, the get
method that we are calling on the HttpClient
will return an observable. We subscribe
to this observable, which allows us to grab the response from the request.
In short, an observable provides a “stream” of data. By “subscribing” to that stream, we can listen for that data and do something when it arrives. In the example above, we are just simply logging out the response that the server sends us. Among other things, observables are a way for us to deal with asynchronous operations in our applications – meaning we can continue running our application whilst some other request is running in the background. If loading the data from the server is going to take 3 seconds, we don’t want to make our application freeze and wait until that has finished executing.
For a more detailed introduction to observables, you may want to watch: An Introduction to Observables for Ionic.
Since observables provide a “stream” of data, meaning that the “subscribe” handler for an observable could be triggered many times, you might think that if you were to run the following code:
this.http.get('https://someapi.com/posts').subscribe((response) => {
console.log(response);
});
That the console.log(response)
line would be triggered every time that the posts
on the server changes – in essence, you could update your application every time a new post is added on the server. This is a common misconception, but it is not the case. Generally, the observable provided by the HttpClient
will only fire once.
If you want to stream data live from a server then you would want to look into websockets.
GET Requests (Retrieving Data)
A GET request will allow us to retrieve data from a particular URL. We have already covered what that looks like, but let’s take another look:
this.http.get('https://someapi.com/posts').subscribe((response) => {
console.log(response);
});
We call the get
method and supply it with the URL that we want to make the request to. Once the server has sent its response to our request, it will trigger the handler we set up using subscribe
. The response
will contain the data we were attempting to request.
As well as fetching data from a remote URL, we can also use a GET request to load data from a local file. That might look something like this:
this.http.get('assets/some-data.json').subscribe((response) => {
console.log(response);
});
This file should be stored along with your applications other static assets in the assets folder.
POST Requests (Sending Data)
As well as fetching data from a server, we can also send data to a server through a POST request. A POST request is very similar in nature to a GET request, except that it also contains an additional body/payload parameter:
this.http
.post('https://someapi.com/posts', {
content: 'hello',
submittedBy: 'Josh',
})
.subscribe((response) => {
console.log(response);
});
This would allow the server to retrieve the following data from our POST request:
{
content: 'hello',
submittedBy: 'Josh'
}
The server would then likely use that data to create a new “post”. Notice that the POST request still subscribes to the observable for a response. Observables are not executed until they are subscribed to, so it is important that you do this. However, even though we might not technically need the response we get, a POST request can still send a response just like a GET request can. We might use this just to verify that the server received and executed the request correctly, or we might get some other useful information back from the server.
If you would like a more detailed introduction to creating POST requests and handling them on a server, take a look at the following article: Sending Data with POST Requests to a NestJS Backend.
Summary
For a lot of people, especially beginners, you likely won’t need to do anything much harder than what you have read in this article. However, there is a lot more you can do with GET/POST requests and with observables in general for more advanced/complex situations.