Angular HTTP and RESTful APIs

Chapter 8: Angular HTTP and RESTful APIs

In this chapter, we will explore how to make HTTP requests in Angular using the HttpClient module. We will learn how to consume RESTful APIs, handle asynchronous operations with Observables, handle errors, and even integrate JWT authentication into our API calls.

Section 1: Making HTTP Requests with HttpClient

  1. Import the necessary modules and inject the HttpClient service:
import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }
  1. Make an HTTP GET request and handle the response asynchronously:
this.http.get('https://api.example.com/data')
  .subscribe(
    (response) => {
      // Handle the response data here
      console.log(response);
    },
    (error) => {
      // Handle any errors that occur during the request
      console.error(error);
    }
  );

Section 2: Consuming RESTful APIs

  1. Make an HTTP POST request to send data to a RESTful API:
const data = { name: 'John Doe', email: 'johndoe@example.com' };

this.http.post('https://api.example.com/users', data)
  .subscribe(
    (response) => {
      // Handle the response data here
      console.log(response);
    },
    (error) => {
      // Handle any errors that occur during the request
      console.error(error);
    }
  );
  1. Make an HTTP PUT request to update data in a RESTful API:
const data = { name: 'John Doe', email: 'johndoe@example.com' };

this.http.put('https://api.example.com/users/1', data)
  .subscribe(
    (response) => {
      // Handle the response data here
      console.log(response);
    },
    (error) => {
      // Handle any errors that occur during the request
      console.error(error);
    }
  );

Section 3: Handling Asynchronous Operations with Observables

  1. Use the map operator to transform the response data:
import { map } from 'rxjs/operators';

this.http.get('https://api.example.com/data')
  .pipe(
    map((response) => {
      // Transform the response data here
      return response.map(item => item.name);
    })
  )
  .subscribe(
    (transformedData) => {
      // Handle the transformed data here
      console.log(transformedData);
    },
    (error) => {
      console.error(error);
    }
  );

Section 4: Handling Errors and HTTP Interceptors

  1. Create an HTTP interceptor to handle errors globally:
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

export class ErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error) => {
        // Handle the error here
        console.error(error);
        return throwError(error);
      })
    );
  }
}
  1. Register the interceptor in your app.module.ts file:
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorInterceptor } from './error.interceptor';

@NgModule({
  // Other module configurations
  providers: [
    // Other providers
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
  ],
})
export class AppModule { }

By implementing the above code examples and concepts, you will be able to effectively make

HTTP requests, consume RESTful APIs, handle asynchronous operations using Observables, and handle errors in your Angular application. Additionally, you can enhance the code to include JWT authentication by appending the necessary headers to the HTTP requests.