HTTP & Data
HTTP Communication
The frontend is an isolated island. The HttpClient is the bridge to the mainland (backend). Based on RxJS and more powerful than the standard Fetch.
When I switched from React to Angular, I thought: "Why not just use fetch()?"
The answer is control. The Angular HttpClient does not return simple promises but observables. That may sound complicated, but it means: I can cancel ongoing requests, measure progress, and handle errors centrally.
1. Request Simulator
Observe the dialogue between the app and the server. On the left, you see what the user sees (UI). On the right, you see the raw JSON data that is actually transmitted.
2. Implementation
Since Angular 15+ (Standalone), the setup is extremely streamlined. We no longer need to import modules but simply provide a provider.
Step 1: Global Setup
In app.config.ts, we enable the client. My tip: Be sure to use withFetch(). This ensures that Angular uses the modern Fetch API under the hood, which is essential for SSR (Server Side Rendering).
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(
// 1. Performance: Uses native Fetch API (Important for SSR!)
withFetch(),
// 2. Security: Automatically attach auth token
withInterceptors([authInterceptor])
)
]
};Step 2: The Service
I never write HTTP calls directly in the component. The logic belongs in a service. My most important tip: Use generics! Write get<User[]>(...) instead of just get(...). This way, you immediately get autocomplete for the data.
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// Best Practice: Define an interface
export interface User {
id: number;
name: string;
email: string;
}
@Injectable({ providedIn: 'root' })
export class UserService {
private http = inject(HttpClient);
private apiUrl = 'https://api.my-backend.com';
getUsers() {
// Generics <User[]> ensure autocomplete throughout the project
return this.http.get<User[]>(this.apiUrl + '/users');
}
getUserById(id: number) {
return this.http.get<User>(this.apiUrl + '/users/' + id);
}
createUser(user: User) {
return this.http.post<User>(this.apiUrl + '/users', user);
}
}Cold Observables: An HTTP request in Angular is like ordering a pizza. Just because you wrote the order (called the function), no pizza is delivered yet.
The request is only sent when you subscribe (.subscribe() or AsyncPipe). Without a subscription, nothing happens.