Angular Tutorial
HTTP Client (API Requests)
Almost every application requires communicating with a backend server or Database mapping (like a Node.js API, Python Django, or Spring Boot) via HTTP requests. Angular completely abstracts standard browser fetch() APIs into a highly robust, testable, and reactive service called HttpClient.
Providing HttpClient (Modern Angular)
In modern standalone architectures (Angular 15+), you supply the global HTTP mechanism in your app.config.ts root file.
// app.config.ts
import { provideHttpClient } from '@angular/common/http';
export const appConfig = {
providers: [provideHttpClient()]
};Creating the Service
As an absolute rule of thumb, you should NEVER inject HttpClient directly into a Component. Instead, you create a dedicated API Service to act as an intermediary, making the code incredibly clean and reusable.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs'; // Important!
// Define the interface shape of your API Data
export interface Product { id: number; name: string; price: number; }
@Injectable({ providedIn: 'root' })
export class ApiService {
private BASE_URL = 'https://api.example.com/products';
constructor(private http: HttpClient) {}
// GET Request (Retrieves data)
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(this.BASE_URL);
}
// POST Request (Sends new data)
createProduct(newProduct: Partial<Product>): Observable<Product> {
return this.http.post<Product>(this.BASE_URL, newProduct);
}
// DELETE Request
deleteProduct(id: number): Observable<any> {
return this.http.delete(`${this.BASE_URL}/${id}`);
}
}Subscribing in the Component
Unlike Promises (from fetch or axios), Angular uses Observables. An HTTP Observable will absolutely NOT execute the network request until someone manually subscribe()s to it!
import { Component, OnInit } from '@angular/core';
import { ApiService, Product } from './api.service';
@Component(...)
export class ProductListComponent implements OnInit {
products: Product[] = [];
isLoading = false;
constructor(private api: ApiService) {}
ngOnInit() {
this.isLoading = true;
// The network request triggers once we subscribe!
this.api.getProducts().subscribe({
next: (data) => {
this.products = data;
this.isLoading = false;
},
error: (err) => {
console.error("API Failed!", err);
this.isLoading = false;
}
});
}
}Interceptors
Angular provides HTTP Interceptors, allowing you to intercept outgoing requests and incoming responses globally. This is heavily used to automatically append an Authorization: Bearer [TOKEN] header for authentication to every single request on your site invisibly.
Conclusion
You've now seen the word Observable and subscribe(). What exactly are they? They are the core of Reactive Programming in Angular, handled by the RxJS Library, which we explore completely in the next chapter.