angular
/

Angular HttpClient – Communicating with APIs

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

angular

Angular HttpClient – Communicating with APIs

What is the HttpClient?

In modern web applications, the frontend rarely exists in isolation. It needs to communicate with backend microservices, databases, and third-party APIs. Angular provides the HttpClient service, a powerful and robust API for making HTTP requests. Unlike the standard browser fetch API, Angular's HttpClient is built entirely around RxJS Observables, allowing for advanced features like request cancellation, retries, and data transformation streams.

  1. Setup and Configuration

In modern Angular (v15+), you configure the HTTP client at the application level using the provideHttpClient() function in your main configuration file, rather than importing the older HttpClientModule.

TypeScriptRead-only
1
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';

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

  1. Making Strongly-Typed Requests

As a best practice, you should always define TypeScript interfaces for your expected API responses. You can pass these interfaces as Generics to the HttpClient methods to ensure type safety throughout your application.

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

export interface Project {
  id: string;
  name: string;
  status: string;
}

@Injectable({ providedIn: 'root' })
export class ProjectService {
  private apiUrl = 'https://api.example.com/v1/projects';

  constructor(private http: HttpClient) {}

  // GET Request
  getProjects(): Observable<Project[]> {
    return this.http.get<Project[]>(this.apiUrl);
  }

  // POST Request
  createProject(project: Partial<Project>): Observable<Project> {
    return this.http.post<Project>(this.apiUrl, project);
  }
}

  1. HttpInterceptors (Enterprise Standard)

Interceptors are one of the most powerful architectural features in Angular. They sit between your application and the network, allowing you to inspect and modify outgoing requests (e.g., adding Authorization headers) and incoming responses (e.g., global error handling) without cluttering your component or service logic.

TypeScriptRead-only
1
import { HttpInterceptorFn } from '@angular/common/http';

// A functional interceptor to attach JWT tokens
export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const authToken = localStorage.getItem('access_token');
  
  if (authToken) {
    // Requests are immutable, so we must clone it to modify headers
    const clonedRequest = req.clone({
      setHeaders: { Authorization: `Bearer ${authToken}` }
    });
    return next(clonedRequest);
  }
  
  return next(req);
};

Common HTTP Methods Summary

MethodTypical Use CaseIdempotent
GETRetrieve data from the serverYes
POSTCreate a new record/resourceNo
PUTUpdate an entire existing resourceYes
PATCHPartially update an existing resourceNo
DELETERemove a resource from the serverYes

Test Your Knowledge

Q1
of 3

Which function is used to configure the HttpClient in a modern Angular application's configuration file?

A
importHttpClient()
B
provideHttpClient()
C
setupHttp()
D
HttpClientModule()
Q2
of 3

What must you do to an Observable returned by HttpClient to actually execute the network request?

A
Call the .execute() method
B
Wrap it in a Promise
C
Subscribe to it
D
Import the HttpModule
Q3
of 3

Which feature allows you to globally modify outgoing HTTP requests, such as attaching an authentication token?

A
HttpRouter
B
HttpGuard
C
HttpInterceptor
D
HttpModifier

Frequently Asked Questions

Why does my HTTP request not fire?

Observables returned by HttpClient are 'cold'. This means the actual network request is not sent until you explicitly .subscribe() to the Observable in your component or use the async pipe in your template.

How do I handle API errors?

You should use the catchError RxJS operator within the pipe() method of your request. This allows you to log the error, return a fallback value, or throw a user-friendly error message before it reaches the component.

What is the difference between HttpClient and the browser's Fetch API?

While Fetch uses Promises (which execute immediately and cannot be easily cancelled), HttpClient uses Observables. This provides advanced capabilities like request cancellation, easy retries, and seamless integration with Angular's testing utilities.

Previous

angular form validation

Next

angular interceptors

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.