Learn Angular · 7/14

HTTP Client: Communicating with Backend APIs

7 min read

Course: Angular
Status: 🟢 Active
Difficulty: ⭐⭐⭐☆☆


1. Configuring provideHttpClient and Making GET Requests

🔹 The Problem

Imagine you have built a beautiful user interface for a weather application. It has icons, strict typing, and a perfect layout. However, the temperature always says "0°C" because your app lives in isolation. It has no way to "speak" to the outside world to get real live data.

In the past (before Angular 15+), developers had to import a heavy HttpClientModule into a complex file called AppModule. It was boilerplate-heavy and often confusing for beginners.

🔹 The Solution

Angular now uses Standalone Components by default. To enable communication with the outside world, we use a streamlined function called provideHttpClient. Think of this as giving your application a "voice" and "ears" to send messages (requests) and listen for answers (responses).

Once configured, we use the HttpClient service to make GET requests—the digital equivalent of asking, "Hey, can I see that data?"

🛠️ Step-by-Step Implementation

1. Configure the Application

In a modern standalone app, we register the HTTP client in our application configuration file, usually app.config.ts.

typescript
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    // 💡 This single line unlocks all HTTP capabilities
    provideHttpClient()
  ]
};

2. Create an Interface

Always define the shape of your data first. It keeps your code predictable.

typescript
// user.interface.ts
export interface User {
  id: number;
  name: string;
  email: string;
}

3. Inject and Request

Now, let's fetch data in a service. We use Dependency Injection to get the HttpClient.

typescript
// user.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from './user.interface';

@Injectable({ providedIn: 'root' })
export class UserService {
  // 🆕 Modern injection style (no constructor needed)
  private http = inject(HttpClient);
  
  private apiUrl = 'https://jsonplaceholder.typicode.com/users';

  getUsers(): Observable<User[]> {
    // We tell Angular: "Expect the result to be an array of Users"
    return this.http.get<User[]>(this.apiUrl);
  }
}

4. Displaying Data

In your component, you "subscribe" to the data.

Note: HttpClient returns an Observable. Nothing happens until you subscribe (like buying a newspaper subscription—you don't get news until you sign up).

typescript
// user-list.component.ts
import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common'; // for *ngFor
import { UserService } from './user.service';
import { User } from './user.interface';

@Component({
  selector: 'app-user-list',
  standalone: true,
  imports: [CommonModule],
  template: `
    <ul>
      <li *ngFor="let user of users">
        {{ user.name }} ({{ user.email }})
      </li>
    </ul>
  `
})
export class UserListComponent implements OnInit {
  private userService = inject(UserService);
  users: User[] = [];

  ngOnInit() {
    this.userService.getUsers().subscribe((data) => {
      this.users = data;
      console.log('Data received! 📬');
    });
  }
}

2. Sending Data: POST, PUT, and DELETE Requests

🔹 The Problem

Fetching data (GET) is safe because it doesn't change anything on the server. But real applications need to create new accounts, update profiles, or delete posts. If GET is reading a book, these operations are writing, editing, and ripping out pages.

🔹 The Solution

RESTful APIs use specific "verbs" for these actions:

  • POST: Create something new.
  • PUT: Update an existing item fully.
  • DELETE: Remove an item.

The HttpClient provides methods matching these names. They all return Observables, so you must subscribe to execute them.

🛠️ Implementation

Let's expand our UserService to handle these operations.

typescript
// user.service.ts (continued)

// 1. POST: Create a new user
createUser(newUser: Omit<User, 'id'>): Observable<User> {
  return this.http.post<User>(this.apiUrl, newUser);
}

// 2. PUT: Update a user (we need the ID to know who to update)
updateUser(id: number, updatedData: User): Observable<User> {
  return this.http.put<User>(`${this.apiUrl}/${id}`, updatedData);
}

// 3. DELETE: Remove a user
deleteUser(id: number): Observable<void> {
  return this.http.delete<void>(`${this.apiUrl}/${id}`);
}

💡 Usage in Component

Notice how we handle the response. For DELETE, the response is often empty (void), just a confirmation that "it is done."

typescript
// creating a user
this.userService.createUser({ name: 'Alice', email: '[email protected]' })
  .subscribe(createdUser => {
    console.log('User created with ID:', createdUser.id);
    this.users.push(createdUser); // Update UI instantly
  });

// deleting a user
this.userService.deleteUser(5)
  .subscribe(() => {
    console.log('User 5 deleted');
    // Filter out the deleted user from the local list
    this.users = this.users.filter(u => u.id !== 5);
  });

Fun Fact 🎈: The DELETE method is sometimes called the "void pointer of the web." If it works, you get nothing back but a status code 204 (No Content). It's the most "silent" successful interaction in programming.


3. Handling HTTP Errors Gracefully

🔹 The Problem

The internet is fragile. Servers crash, Wi-Fi drops, and users go into tunnels. If your app crashes or shows a blank white screen when an API call fails, users will think your app is broken.

🔹 The Solution

We use RxJS Operators, specifically catchError. This allows us to "intercept" the crash before it reaches the component, log it, and return a "fallback" value or a safe error message.

🛠️ Implementation

We will improve the service to handle errors using catchError and throwError.

typescript
import { catchError, throwError } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

// inside UserService

getUsers(): Observable<User[]> {
  return this.http.get<User[]>(this.apiUrl).pipe(
    // 🛡️ The catchError operator catches the crash
    catchError(this.handleError)
  );
}

private handleError(error: HttpErrorResponse) {
  let errorMessage = 'Unknown error!';
  
  if (error.error instanceof ErrorEvent) {
    // Client-side error (e.g., network disconnected)
    errorMessage = `Client Error: ${error.error.message}`;
  } else {
    // Server-side error (e.g., 404 Not Found, 500 Server Error)
    errorMessage = `Server Error Code: ${error.status}\nMessage: ${error.message}`;
  }
  
  console.error(errorMessage);
  
  // Return an observable with a user-facing error message
  return throwError(() => new Error('Something went wrong. Please try again later.'));
}

In the Component:
Now the component can handle the specific "clean" error.

typescript
this.userService.getUsers().subscribe({
  next: (data) => this.users = data,
  error: (err) => this.errorMessage = err.message // Display this in UI
});

4. HTTP Interceptors: Attaching Auth Tokens and Headers

🔹 The Problem

You have 50 different API calls. Every single one needs an Authorization header (like Bearer xyz123) to prove the user is logged in. Manually adding { headers: ... } to every http.get() and http.post() call is repetitive, error-prone, and violates the "DRY" (Don't Repeat Yourself) principle.

🔹 The Solution

Interceptors. Think of an interceptor as a security guard or a mailroom clerk that sits between your app and the internet. Every request leaving your app must pass through this clerk. The clerk can stamp a token on the envelope automatically before sending it out.

Since Angular 15+, we use Functional Interceptors (HttpInterceptorFn), which are lighter and easier than the old class-based ones.

🛠️ Implementation

1. Define the Interceptor Function

typescript
// auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  // 1. Get the token (simulated here)
  const myToken = 'SECRET_TOKEN_123';

  // 2. Clone the request
  // (Requests are immutable/read-only, so we must make a copy to change it)
  const clonedRequest = req.clone({
    setHeaders: {
      Authorization: `Bearer ${myToken}`
    }
  });

  console.log(`📤 Intercepting request to: ${req.url}`);

  // 3. Pass the modified request to the next handler
  return next(clonedRequest);
};

2. Register the Interceptor

Go back to app.config.ts and add it to your HTTP configuration.

typescript
// app.config.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './auth.interceptor';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(
      // 🔗 Chain your interceptors here
      withInterceptors([authInterceptor]) 
    )
  ]
};

Now, every request you make with HttpClient will automatically have the Authorization header attached. You never have to write it manually again.


📝 Summary Checklist

  1. Setup: Used provideHttpClient() in app.config.ts.
  2. Read: Used http.get<T>() to fetch data.
  3. Write: Used post, put, and delete to mutate data.
  4. Safety: Used catchError to handle failures gracefully.
  5. Efficiency: Used withInterceptors to automate headers.

Imagination Corner 🧠:
If Observables were water pipes, HttpClient is the faucet, and subscribe() is you turning the handle. If you don't turn the handle (subscribe), no water (data) flows, no matter how nice the plumbing is. This is why we call them "Cold Observables."


🔗 References & Further Reading

Challenge

You are tasked with implementing a full-featured data management service in an Angular application. This involves defining the data model, creating a service with complete CRUD (Create, Read, Update, Delete) operations, implementing robust error handling, and securing API requests with an authentication token interceptor.

Your goal is to fill in the missing logic in the provided code skeleton, which is structured as multiple files within a single editor block.

Requirements:

  1. Product Interface: In the designated section for product.model.ts, define a Product interface with the following properties: id (number), name (string), and price (number).

  2. Authentication Interceptor: In the auth.interceptor.ts section, implement a functional HttpInterceptorFn named authInterceptor. This interceptor must add an Authorization header to every outgoing HTTP request. The header's value should be the static string 'Bearer FAKE_JWT_TOKEN'. Remember that HttpRequest objects are immutable, so you must clone the request to modify it.

  3. Product Service (ProductService):

    • Implement the getProducts() method to fetch an array of Product objects from the apiUrl.
    • Implement the addProduct(product: Product) method to send a new Product to the API via a POST request.
    • Implement the updateProduct(product: Product) method to send an updated Product to https://api.example.com/products/{id} via a PUT request.
    • Implement the deleteProduct(id: number) method to send a DELETE request to https://api.example.com/products/{id}.
  4. Error Handling:

    • Within the ProductService, fully implement the private handleError method. It should differentiate between client-side (error.status === 0) and server-side errors, log appropriate details to the console, and use throwError from RxJS to return a new observable with a user-friendly error message.
    • For all four CRUD methods, you must pipe the HttpClient call through RxJS's catchError operator and pass your handleError method as the argument.
  5. Application Configuration:

    • In the app.config.ts section, correctly configure the application's providers array. Use provideHttpClient and withInterceptors to enable HttpClient globally and register your authInterceptor.

Expected result

Your solution should contain the completed implementation for the Product interface, the ProductService, the authInterceptor, and the appConfig.

1. product.model.ts

The Product interface should be correctly defined with the specified properties and types.

typescript
export interface Product {
  id: number;
  name: string;
  price: number;
}

2. auth.interceptor.ts

The interceptor must clone the incoming request, set the Authorization header, and pass the new request to the next handler. This ensures all requests are sent with the required token without modifying the original request object.

typescript
import { HttpInterceptorFn } from '@angular/common/http';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
    const authToken = 'Bearer FAKE_JWT_TOKEN';
    const authReq = req.clone({
        setHeaders: {
            Authorization: authToken
        }
    });
    return next(authReq);
};

3. product.service.ts

The service should have all CRUD methods implemented, each returning an Observable from an HttpClient call. Crucially, each method must pipe its result through the catchError operator, which delegates to the handleError method for centralized, robust error management.

typescript
@Injectable({
  providedIn: 'root'
})
export class ProductService {
  private apiUrl = 'https://api.example.com/products';
  private http = inject(HttpClient);

  private handleError(error: HttpErrorResponse) {
    if (error.status === 0) {
      console.error('An error occurred:', error.error);
    } else {
      console.error(`Backend returned code ${error.status}, body was: `, error.error);
    }
    return throwError(() => new Error('Something bad happened; please try again later.'));
  }

  getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(this.apiUrl).pipe(catchError(this.handleError));
  }

  addProduct(product: Product): Observable<Product> {
    return this.http.post<Product>(this.apiUrl, product).pipe(catchError(this.handleError));
  }

  updateProduct(product: Product): Observable<any> {
    return this.http.put(`${this.apiUrl}/${product.id}`, product).pipe(catchError(this.handleError));
  }

  deleteProduct(id: number): Observable<Product> {
    return this.http.delete<Product>(`${this.apiUrl}/${id}`).pipe(catchError(this.handleError));
  }
}

4. app.config.ts

The application configuration must use provideHttpClient with the withInterceptors function to correctly register the HttpClient service and apply the functional interceptor to all outgoing requests.

typescript
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './auth.interceptor'; // Assuming files are in the same directory

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withInterceptors([authInterceptor]))
  ]
};
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.