Angular HTTP Client

Angular provides an HTTP client module to handle HTTP requests and responses. It simplifies the process of making HTTP requests by providing a set of easy-to-use methods that can be used to interact with any web API.

The HttpClient module provides a number of features, including:

  • Making HTTP requests: The HTTP client module provides a set of methods for making HTTP requests, such as GET, POST, PUT, DELETE, etc. These methods can be used to interact with any web API that provides an HTTP interface.
  • Observables: The HttpClient module uses observables to handle asynchronous requests. Observables are a powerful tool in Angular, allowing developers to subscribe to a stream of events and react accordingly.
  • Interceptors: Interceptors allow you to intercept HTTP requests and responses before they are sent or received. This allows you to add additional logic to requests or responses, such as adding headers, logging, or handling errors.
  • Error handling: The HttpClient module provides a number of options for handling errors, including retrying failed requests, handling HTTP errors, and catching network errors.
  • Caching: The HttpClient module supports caching, allowing you to cache responses and reduce the number of requests made to the server.

 

Here is an example of how to use the HttpClient module in an Angular application:

  1. Import the HttpClientModule into your app.module.ts file: 
    import { HttpClientModule } from '@angular/common/http';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
        AppComponent,
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
      ],
      providers: [],
    })
    export class AppModule {
      constructor() {}
    }
    
  2. Inject the HttpClient service into your service:
    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs';
    import { environment } from 'src/environments/environment';
    import { HttpService } from '../config/http-config/http.service';
    
    @Injectable({
      providedIn: 'root'
    })
    export class AppService {
    
      constructor(private http: HttpClient) { }
    
      // This example demonstrates how to make a GET request to retrieve data from the specified URL. 
      // The response is an observable, which can be subscribed to in order to get the data.
       
      getAllPost(): Observable<any> {
        return this.http.get('https://jsonplaceholder.typicode.com/posts');
      }
    
      
      // This example demonstrates how to make a POST request with a JSON body to the specified URL. 
      // The HttpHeaders object is used to set the Content-Type header to 'application/json'.
      
      createPost(body:Object): Observable<any> {
        const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
        return this.http.post('https://jsonplaceholder.typicode.com/posts', body, { headers });
      }
    
      
      // This example demonstrates how to make a PUT request with a JSON body to the specified URL. 
      // The URL includes the ID of the resource being updated.
      
      updatePost(id:string, body:Object): Observable<any> {
        const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
        const url = 'https://jsonplaceholder.typicode.com/posts/' + id;
        return this.http.put(url, body, { headers });
      }
    
    
      // This example demonstrates how to make a PATCH request with a JSON body to the specified URL. 
      // The URL includes the ID of the resource being updated.  
      
      patchPost(id:string, body:Object): Observable<any> {
        const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
        const url = 'https://jsonplaceholder.typicode.com/posts/' + id;
        return this.http.patch(url, body, { headers });
      }
      
    
      // This example demonstrates how to make a DELETE request to the specified URL. 
      // The URL includes the ID of the resource being deleted.
    
      deletePost(id: string): Observable<any> {
        const url = 'https://jsonplaceholder.typicode.com/posts/' + id;
        return this.http.delete(url);
      }
    
      
      
    
    }
    
  3. Inject the AppService service file into your component:
    import { Component, OnInit } from '@angular/core';
    import { AppService } from './app.service';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit{
      constructor(private service: AppService) {}
    
      ngOnInit() {
        this.service.getAllPost().subscribe(data => {
          console.log(data);
        });
      }
    }
    

     

This example makes a GET request to the JSONPlaceholder API and logs the response data to the console. The subscribe method is used to handle the asynchronous response.

Conclusion

The HttpClient module is a powerful tool in Angular that simplifies the process of making HTTP requests. Its features, including observables, interceptors, error handling, caching, and more, make it a must-have for any Angular developer building web applications that interact with APIs.