In this tutorial, we will explore how to make HTTP GET requests in Angular. We will start by creating an Angular application using the Angular CLI and then use the HttpClient module to make GET requests to a REST API.
What is HTTP?
HTTP stands for Hypertext Transfer Protocol. It is the protocol used by the World Wide Web to transfer data between web servers and web clients (i.e., web browsers). HTTP is a request-response protocol in which the client sends a request to the server and the server sends a response back to the client.
What is REST?
REST stands for Representational State Transfer. It is a type of architectural design used to create distributed systems. RESTful web services are built on top of HTTP and use HTTP methods (such as GET, POST, PUT, and DELETE) to perform CRUD (Create, Read, Update, Delete) operations on resources.
What is Angular?
Angular is a most popular JavaScript framework and used to build quick web applications with minimal effect. It is developed and maintained by Google and provides a rich set of features for building complex applications. Angular uses a component-based architecture, in which each component is a self-contained unit of code that can be reused across multiple applications.
Creating an Angular Application
Before we start making HTTP requests, let’s create a new Angular application using the Angular CLI. Open your commend terminal and run the below command:
1 2 3 4 5 |
--- ng new http-demo --- |
This will create a new Angular application in a directory called http-demo
. Navigate to this directory by running:
1 2 3 4 5 |
--- cd http-demo --- |
Now, let’s generate a new component that we will use to make the HTTP request. Run the following command:
1 2 3 4 5 |
--- ng generate component posts --- |
This will generate a new component called PostsComponent
in the src/app/posts
directory. Open this component by running:
1 2 3 4 5 |
--- cd src/app/posts --- |
We are now ready to start making HTTP requests.
Making an HTTP GET Request
To make an HTTP GET request, we need to import the HttpClient
module from the @angular/common/http
package. We also need to inject the HttpClient
service into our component.
Open the posts.component.ts
file and add the following imports:
1 2 3 4 5 6 |
--- import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; --- |
Now, inject the HttpClient
service into the constructor of our component:
1 2 3 4 5 |
--- constructor(private http: HttpClient) {} --- |
We can now use the http.get()
method to make a GET request to a REST API. Let’s make a request to the JSONPlaceholder API, which provides fake JSON data for testing purposes.
Add the following method to our PostsComponent
class:
1 2 3 4 5 6 7 |
--- getPosts() { return this.http.get('https://jsonplaceholder.typicode.com/posts'); } --- |
Include – Request headers
With a couple of headers set, such as the HTTP Authorization header
and a few other essential header
parameters, the same request is sent out again.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
--- getPosts() { const headers = { 'Authorization': 'Bearer auth-token-key', 'user-header1': 'value1', 'user-header2': 'value2' } this.http.get('https://jsonplaceholder.typicode.com/posts', { headers }).subscribe(data => { return data; }); } --- |
Include – Error handling
This makes a request to an invalid URL on the API call, logs the error to the console, and assigns the error to the component attribute errorMessage
.
The next()
function is called if the request is successful, while the error()
function is invoked if the request fails. Both callback functions are contained in the object supplied to the request subscribe()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
--- getPosts() { this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe({ next: data => { return data; }, error: error => { return error.message; console.log('There was an error!', error); } }) } --- |
This method makes a GET request to the https://jsonplaceholder.typicode.com/posts
URL and returns an observable of the response.
Now, let’s use this method to display the list of posts in our component. Add the following code to the posts.component.html
template:
1 2 3 4 |
<h1>Post</h1> <ul> <li *ngFor="let post of posts | async">{{ post.title}}</li> </ul> |
This code displays a list of posts using the *ngFor
directive. The posts
variable is an observable that will be populated with the response from our HTTP request.
Finally, let’s call the getPosts()
method in the ngOnInit()
lifecycle hook:
1 2 3 4 5 6 7 8 |
--- posts:any; ngOnInit() { this.posts = this.getPosts(); } --- |
This will call the getPosts()
method and populate the posts
observable with the response.
Configuring the Routes:
To configure the router, add following code block into your app.module.ts file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
... import { Routes, RouterModule } from '@angular/router'; and const routes: Routes = [ {path:'posts', component:PostsComponent} ]; and RouterModule.forRoot(routes), ... |
Include Http Client Module with APP:
Next, we have to import HttpClientModule
in app.module.ts file and include imports
array object.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
... import { HttpClientModule } from '@angular/common/http'; and imports: [ ... HttpClientModule, ... ], ... |
Include Router Outle:
Next, we have to import router-outlet in relevant app layout file, here i added in app.component.html
file.
1 2 3 4 5 |
.... <router-outlet></router-outlet> .... |
Conclusion
In conclusion, making HTTP GET requests in Angular is a straightforward process that can be achieved using the HttpClient
module. We have learned how to make GET requests to a remote API using various methods such as subscribing to the Observable, mapping the data, and handling errors. We also covered some of the best practices for writing clean and readable code.
It’s essential to keep in mind that HTTP requests can be slow and time-consuming. Thus, it’s crucial to implement caching, pagination, and other performance optimizations to improve the overall user experience. With the knowledge gained from this post, we hope you can build robust and efficient Angular applications that can fetch data from remote APIs with ease.