HttpClient in Angular

Angular provides a built-in service called HttpClient to make HTTP requests to REST APIs. You can use it to fetch data (GET), send data (POST), update data (PUT), or delete data (DELETE).


1. What is HttpClient?

HttpClient is part of the @angular/common/http package and is used to perform HTTP requests. It supports features like:

  • Making GET, POST, PUT, DELETE requests
  • Observables for async data
  • Error handling
  • Request and response interceptors

2. Setting Up HttpClientModule

First, import HttpClientModule in your main module file:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

                @NgModule({
                    declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  bootstrap: [AppComponent],
})
export class AppModule {}

3. Fetching Data using GET Request

To fetch data from an API, use the get() method from HttpClient.

Example: Fetch Users from API

Service File: user.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

                @Injectable({
                    providedIn: 'root',
})
export class UserService {
  private apiUrl = 'https://jsonplaceholder.typicode.com/users';

  constructor(private http: HttpClient) {}

  getUsers(): Observable<any[]> {
    return this.http.get<any[]>(this.apiUrl);
  }
}

Component File: app.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';

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

  constructor(private userService: UserService) {}

  ngOnInit() {
    this.userService.getUsers().subscribe((data) => {
      this.users = data;
    });
  }
}

Template File: app.component.html

<h2>User List</h2>
<ul>
  <li *ngFor="let user of users">
    {{ user.name }} - {{ user.email }}
  </li>
</ul>

4. Sending Data using POST Request

To send data to an API, use the post() method.

Example: Submit User Data

Service File: user.service.ts (extended)

postUser(user: any): Observable<any> {
  return this.http.post(this.apiUrl, user);
}

Component File: app.component.ts (extended)

newUser = {
  name: '',
  email: ''
};

submitUser() {
  this.userService.postUser(this.newUser).subscribe((response) => {
    console.log('User posted:', response);
  });
}

Template File: app.component.html (extended)

<h2>Submit New User</h2>
<form (ngSubmit)="submitUser()">
  <input type="text" placeholder="Name" [(ngModel)]="newUser.name" name="name" required />
  <input type="email" placeholder="Email" [(ngModel)]="newUser.email" name="email" required />
  <button type="submit">Submit</button>
</form>

5. Error Handling (Optional)

You can add error handling using RxJS catchError operator.

import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

getUsers(): Observable<any[]> {
  return this.http.get<any[]>(this.apiUrl).pipe(
    catchError((error) => {
      console.error('Error fetching users', error);
      return throwError(() => new Error('Something went wrong!'));
    })
  );
}

Conclusion

The HttpClient in Angular provides a clean and powerful way to communicate with REST APIs. Use GET to retrieve data and POST to send data. Always import HttpClientModule in your app module and use Observables to handle async operations.

With this knowledge, you can easily integrate APIs in your Angular applications!

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!