HttpClient Setup & GET Requests
Angular's built-in HTTP client lets you talk to APIs, fetch data, and handle responses โ all with Observables and TypeScript typing.
HttpClient is Angular's built-in service for making HTTP requests. It wraps the browser's XMLHttpRequest under the hood and returns Observables โ streams of data that you can transform, filter, and combine.
"HttpClient = Swiggy delivery boy โ backend se data laake deta hai."
Key benefits over raw fetch():
- TypeScript typing โ generic types make response data type-safe
- Interceptors โ modify requests/responses globally
- Error handling โ built-in with catchError operator
- Progress events โ track upload/download progress
- Automatic JSON parsing โ no need to call
.json() - Request cancellation โ via RxJS takeUntil or AbortController
NOT fetch() โ while fetch works in Angular, HttpClient has far better features: interceptors, typed responses, progress tracking, and seamless RxJS integration.
To use HttpClient, you must enable it in app.config.ts using provideHttpClient().
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
// other providers...
]
};
"provideHttpClient = delivery app activate karna โ bina iske order nahi dega."
Three ways to provide HttpClient depending on your needs:
// 1. Basic โ no interceptors
provideHttpClient()
// 2. With class-based interceptors (legacy)
provideHttpClient(withInterceptorsFromDi())
// 3. With functional interceptors (new โ recommended)
provideHttpClient(withInterceptors([authInterceptor, loggingInterceptor]))
Once provided, inject it in any component or service:
private http = inject(HttpClient);The most basic HTTP operation: fetch data from a URL.
import { Component, inject, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
interface Biryani {
id: number;
name: string;
price: number;
category: string;
}
@Component({...})
export class MenuComponent implements OnInit {
private http = inject(HttpClient);
biryanis: Biryani[] = [];
ngOnInit() {
this.http.get<Biryani[]>('/api/biryani')
.subscribe(data => {
this.biryanis = data;
});
}
}
"GET = menu maango โ server dedo."
Key points:
<Biryani[]>โ the generic type tells TypeScript what shape the response has.subscribe()โ the Observable is LAZY; it doesn't fire until you subscribe- HttpClient automatically parses JSON response โ no
.json()call needed
Often you need to pass query parameters โ filters, sorting, pagination.
Old way (Angular 16 and earlier):
import { HttpParams } from '@angular/common/http';
const params = new HttpParams()
.set('category', 'chicken')
.set('sort', 'price')
.set('page', '1');
this.http.get<Biryani[]>('/api/biryani', { params })
.subscribe(data => this.biryanis = data);
New way (Angular 17+ โ object syntax):
this.http.get<Biryani[]>('/api/biryani', {
params: {
category: 'chicken',
sort: 'price',
page: '1'
}
}).subscribe(data => this.biryanis = data);
"Parameters = filters โ sirf chicken biryani chahiye, mutton nahi."
The object syntax is cleaner and more readable. Angular automatically encodes the parameters into URL query string format: /api/biryani?category=chicken&sort=price&page=1.
You can use relative or full URLs when making HTTP requests.
Relative URL:
this.http.get('/api/biryani')
// Uses current origin: https://myapp.com/api/biryani
Full URL:
this.http.get('https://api.hyderabad.com/v2/biryani')
// Full URL โ no origin calculation
"Relative = ghar se order, Full = dusre city se order."
Best practice: Use relative URLs in your services and add the base URL via an interceptor. This way:
- You can change the API URL in one place
- Different environments (dev/staging/prod) can use different base URLs
- Your service code stays clean and portable
// Interceptor adds base URL
export const baseUrlInterceptor: HttpInterceptorFn = (req, next) => {
const apiReq = req.clone({
url: `https://api.hyderabad.com${req.url}`
});
return next(apiReq);
};Key Takeaways
- โ HttpClient is Angular's built-in HTTP service โ better than fetch() with interceptors, typing, and RxJS
- โ Enable with provideHttpClient() in app.config.ts โ inject via inject(HttpClient)
- โ http.get<Type>(url) returns an Observable โ must subscribe() to fire the request
- โ Pass query params via object syntax: { params: { key: 'value' } } (Angular 17+)
- โ Use relative URLs in services and add base URL via interceptor for environment flexibility
Want to track your progress?
Log in to save your place and pick up where you left off.
Progress track karna chahte ho?
Login karo apni progress save karne ke liye aur jahan chhoda tha wahan se shuru karo.
Login