DEV Community

Cover image for Angular HttpClient: A Comprehensive Guide
josematoswork
josematoswork

Posted on • Originally published at angulardive.com

Angular HttpClient: A Comprehensive Guide

Angular HttpClient: A Comprehensive Guide

If you are an Angular developer, you might have come across Angular's built-in HttpClient module that enables you to interact with a server-side API. In this article, we will dive deep into the HttpClient module and explore its features while providing practical examples.

Why Use Angular HttpClient?

One of the primary reasons why developers prefer using HttpClient over other third-party libraries is that it comes pre-installed with Angular, hence no need to install and configure additional dependencies. Additionally, the module is lightweight and easy to use, making it a perfect choice for simple to medium-scale projects where you want to interact with a backend API.

How to Use Angular HttpClient

The first step to using the HttpClient module is to import it into your Angular project. To do that, open your Angular component or service file, and add the following code:

import {HttpClient} from '@angular/common/http';

Once you import the HttpClient module, you can then inject it into the component or service constructor as follows:

constructor(private http: HttpClient) { }

After importing and injecting the HttpClient, you can start making HTTP requests to a server-side API using the get, post, put, delete, and patch request methods provided by the HttpClient module.

Sending GET Requests with Angular HttpClient

The GET method is used to retrieve data from a server. In Angular, you can use the http.get() method to make a GET request to a server. Here is an example:

this.http.get('https://api.example.com/data')
  .subscribe((data: any) => {
    console.log(data);
  });

The above code sends a GET request to api.example.com and logs the server's response to the console. The subscribe() method is used to subscribe to the Observable returned by the http.get() method, which allows you to handle the result of the request or any errors that may occur.

Sending POST Requests with Angular HttpClient

The POST method is used to send data to a server. In Angular, you can use the http.post() method to make a POST request to a server. Here is an example:

this.http.post('https://api.example.com/data', { name: 'John Doe', age: 30 })
  .subscribe((data: any) => {
    console.log(data);
  });

The above code sends a POST request to api.example.com and passes an object with the request payload. The result of the API call is logged to the console.

Handling Errors with Angular HttpClient

When interacting with a backend API, errors are inevitable. Therefore, it is essential to handle errors appropriately to avoid unexpected application behavior. In Angular, you can handle errors by adding an error callback to the subscribe method as follows:

this.http.get('https://api.example.com/data')
  .subscribe((data: any) => {
    console.log(data);
  }, (error: any) => {
    console.log(error);
  });

In the above code, if an error occurs during the API call, the error callback logs the error to the console. You can also use additional error handling mechanisms such as retrying failed requests or custom error handling logics.

HTTP Request Headers with Angular HttpClient

You can add headers to your HTTP requests using the headers option provided by the HttpClient module. Here is an example:

const headers = {'Authorization': 'Bearer my-token'};
this.http.get('https://api.example.com/data', { headers })
  .subscribe((data: any) => {
    console.log(data);
  });

In the above code, a bearer token is sent to the server in the request header.

Intercepting HTTP Requests with Angular HttpClient

Angular's HttpClient provides an interception mechanism that allows you to modify or log HTTP requests and responses. To use the interceptor, you create a class that implements the HttpInterceptor interface and add it to the HttpClient provider. Here is an example:

import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const authReq = req.clone({
      headers: req.headers.set('Authorization', 'Bearer my-token')
    });

    return next.handle(authReq);
  }
}

The above code creates an interceptor that adds a bearer token authorization header to every outgoing HTTP request.

Conclusion

The Angular HttpClient module is a powerful tool that enables you to interact with a backend API. In this article, we explored how to use the HttpClient module to make HTTP requests, handle errors, add headers and intercept requests. With this knowledge, you can now take your Angular application's server-side API interaction to the next level.

Top comments (0)