Angular HTTP Client

Making HTTP Requests in Angular Applications

Angular provides the HttpClient module to make HTTP requests to backend APIs.

  • Import HttpClient Module: First, import the HttpClientModule in your root module (typically app.module.ts).
                          
                          import { HttpClientModule } from '@angular/common/http';
                          
                        

  • Inject HttpClient Service: Inject the HttpClient service into your component or service where you want to make HTTP requests.
                          
import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }
                          
                        

Make HTTP Requests: Use methods like get, post, put, delete, etc., provided by the HttpClient service to make HTTP requests.

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

                          
                        

Handling HTTP Responses and Errors

Subscribing to Responses: Subscribe to the Observable that gets generated by means of HTTP request methods with the method subscribe. With data handling done, you can manage either the response data or any errors.

Handling Responses: Implement response information handling within a success function of the subscribe call.

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

                          
                        

Handling Errors: Handle errors within the error callback of the subscribe method.

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

                          
                        

Handling Errors Globally: You can set up a global error handler using Angular's 'HttpInterceptor' to handle HTTP errors across your application.

                          
import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler) {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        console.error('HTTP Error:', error);
        return throwError('Something went wrong. Please try again later.');
      })
    );
  }
}