Angular 20 HTTP Tutorial – API Integration with HttpClient & Interceptors in Standalone Components

Angular 20 HTTP Tutorial – API Integration with HttpClient & Interceptors in Standalone Components

AI Reading

Quick summary of this article

Angular 20 simplifies API integration using standalone components and the HttpClientModule. This guide explains how to set up HTTP services, perform CRUD operations (GET, POST, PUT, DELETE), and handle errors globally using interceptors—all without traditional Angular modules.

  • Import HttpClientModule during app bootstrap to enable HTTP communication across all standalone components.
  • Create injectable services with HttpClient to interact with APIs, returning RxJS Observables for async data handling.
  • Use standalone components with CommonModule and HttpClientModule imports to consume HTTP services and display data.
  • Implement HTTP interceptors to centrally manage errors, such as catching client-side or server-side failures and showing alerts.
  • Register interceptors during bootstrap using the HTTP_INTERCEPTORS token with multi: true to allow multiple interceptors.

Chapter 10: HTTP and API Integration in Angular 20 (Standalone Components)

Interacting with backend APIs is crucial for modern web apps. Angular 20 makes HTTP communication simple and powerful via the HttpClientModule. This chapter covers how to set up HTTP services, perform GET, POST, PUT, and DELETE requests, and handle errors gracefully using interceptors — all using standalone components.

1. Setting up HttpClientModule

Import HttpClientModule during bootstrap or in your standalone component:


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

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

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(HttpClientModule)
  ]
});
  

2. Creating an HTTP Service

Use Angular’s HttpClient to communicate with APIs. Here’s a simple service as a standalone injectable:


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

export interface Todo {
  id: number;
  title: string;
  completed: boolean;
}

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

  constructor(private http: HttpClient) {}

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

  getTodo(id: number): Observable {
    return this.http.get(`${this.apiUrl}/${id}`);
  }

  addTodo(todo: Partial): Observable {
    return this.http.post(this.apiUrl, todo);
  }

  updateTodo(id: number, todo: Partial): Observable {
    return this.http.put(`${this.apiUrl}/${id}`, todo);
  }

  deleteTodo(id: number): Observable {
    return this.http.delete(`${this.apiUrl}/${id}`);
  }
}
  

3. Using HTTP Service in a Standalone Component


import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TodoService, Todo } from './todo.service';
import { HttpClientModule } from '@angular/common/http';

@Component({
  standalone: true,
  selector: 'app-todo-list',
  imports: [CommonModule, HttpClientModule],
  template: `

Todo List

 

    • {{ todo.title }} – {{ todo.completed ? ‘Done’ : ‘Pending’ }}

 

` }) export class TodoListComponent implements OnInit { todos: Todo[] = []; constructor(private todoService: TodoService) {} ngOnInit() { this.todoService.getTodos().subscribe({ next: (data) => this.todos = data, error: (err) => console.error(‘Failed to load todos’, err) }); } }

4. Handling HTTP Errors with Interceptors

Angular interceptors allow centralized request/response handling, great for adding auth headers or handling errors globally.


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

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        let errorMsg = '';
        if (error.error instanceof ErrorEvent) {
          // Client-side error
          errorMsg = `Error: ${error.error.message}`;
        } else {
          // Server-side error
          errorMsg = `Error Code: ${error.status}\nMessage: ${error.message}`;
        }
        alert(errorMsg);
        return throwError(() => errorMsg);
      })
    );
  }
}
  

Registering the Interceptor

Provide the interceptor during bootstrap with HTTP_INTERCEPTORS token:


import { bootstrapApplication } from '@angular/platform-browser';
import { importProvidersFrom } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AppComponent } from './app/app.component';
import { ErrorInterceptor } from './error.interceptor';

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(HttpClientModule),
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ErrorInterceptor,
      multi: true
    }
  ]
});
  

5. Summary

  • Import HttpClientModule to enable HTTP communications in your standalone Angular app.
  • Create injectable services with HttpClient for API CRUD operations.
  • Use RxJS Observables to handle asynchronous HTTP calls.
  • Manage errors centrally using HTTP interceptors.

Next Chapter Preview

Chapter 11 will introduce Standalone Components API in Angular 20 — a modern way to build components and services without Angular modules.

Leave a Reply

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