Lesson 5: HTTP Client and APIs in Angular

In modern web applications, interacting with remote servers through APIs is a common requirement. Angular’s HTTP Client module makes it easier to handle HTTP requests and communicate with APIs. In this lesson, we’ll cover how to use Angular’s HttpClient service to make API calls, handle responses, and work with asynchronous data using Observables.

1. Introduction to Angular HTTP Client

The HttpClient service in Angular is built on top of the RxJS Observables, allowing you to perform asynchronous HTTP operations and handle them efficiently.

Importing HttpClientModule

To use HttpClient in your Angular application, you first need to import the HttpClientModule in your app.module.ts:

TypeScript
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [HttpClientModule]
})
export class AppModule {}

2. Making a GET Request

The GET method is used to fetch data from a remote server. Using HttpClient, you can easily make a GET request and handle the response.

Example: Fetching data from a REST API
TypeScript
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  data: any;

  constructor(private http: HttpClient) {}

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

In this example, the http.get() method is used to make a GET request to the API endpoint, and the response is stored in the data variable.

3. Making a POST Request

A POST request is used to send data to a server to create or update resources. You can use HttpClient to make POST requests by sending data as the second argument.

Example: Sending data to an API using POST
TypeScript
import { HttpClient } from '@angular/common/http';

export class AppComponent {
  constructor(private http: HttpClient) {}

  sendData() {
    const body = { name: 'John', age: 30 };
    this.http.post('https://api.example.com/create', body)
      .subscribe(response => {
        console.log('Data sent successfully!', response);
      });
  }
}

In this example, the http.post() method is used to send the body data to the specified API endpoint.

4. Error Handling

Handling errors in HTTP requests is critical for building reliable applications. Angular provides the catchError operator from RxJS to catch and manage errors.

Example: Error handling with catchError
TypeScript
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

this.http.get('https://api.example.com/data')
  .pipe(
    catchError(error => {
      console.error('Error occurred:', error);
      return throwError(error);  // Rethrow the error for further handling
    })
  )
  .subscribe(
    data => console.log(data),
    error => console.log('Error callback:', error)
  );

The catchError operator allows you to intercept errors and handle them before they propagate through the application.

5. HTTP Interceptors

HTTP Interceptors are useful for modifying HTTP requests and responses globally before they reach the actual service. You can use interceptors to add authentication tokens, handle global error handling, or log requests.

Example: Creating an HTTP Interceptor
TypeScript
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

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

You then provide the interceptor in your app’s module:

TypeScript
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';

@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
  ]
})
export class AppModule {}

6. Working with Observables and Promises

Since HTTP requests are asynchronous, Angular’s HttpClient returns Observables. You can either subscribe to the Observable or convert it to a Promise for more flexibility.

Observables Example:
TypeScript
this.http.get('https://api.example.com/data')
  .subscribe(data => console.log(data));

Converting Observable to Promise:

TypeScript
this.http.get('https://api.example.com/data').toPromise()
  .then(data => console.log(data));

7. Real-World Example: Fetching a List of Users

Let’s put all the concepts together and create a small example of fetching a list of users from an API and displaying it.

Component:
TypeScript
export class AppComponent implements OnInit {
  users: any[] = [];

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get<any[]>('https://jsonplaceholder.typicode.com/users')
      .subscribe(response => {
        this.users = response;
      });
  }
}

Template:

HTML
<ul>
  <li *ngFor="let user of users">
    {{ user.name }} ({{ user.email }})
  </li>
</ul>

Conclusion

In this lesson, we explored how to use the Angular HttpClient module to interact with APIs. You now have the skills to make GET and POST requests, handle errors gracefully, and use interceptors to modify HTTP requests globally. This will enable you to build robust, dynamic web applications that interact with remote servers and services.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top