Services, DI & Communication
Angular HttpClient
HttpClient is Angular’s HTTP API. Its methods return Observables, parse JSON automatically, support typed responses, and integrate with interceptors for cross-cutting concerns such as authentication.
What is HttpClient in Angular?
HttpClient is Angular’s HTTP API. Its methods return Observables, parse JSON automatically, support typed responses, and integrate with interceptors for cross-cutting concerns such as authentication.
HttpClient example
TypeScript
// app.config.ts
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()],
};
// service
@Injectable({ providedIn: 'root' })
export class JobService {
private http = inject(HttpClient);
getJobs(city: string): Observable<Job[]> {
const params = new HttpParams().set('city', city).set('page', 1);
return this.http.get<Job[]>('/api/jobs', { params });
}
create(job: Partial<Job>): Observable<Job> {
return this.http.post<Job>('/api/jobs', job);
}
}Key points to remember
- The request does not fire until something subscribes — an unsubscribed Observable does nothing.
- The async pipe subscribes and unsubscribes for you.
- Use HttpParams for query strings rather than string concatenation.
- A non-2xx response produces an error notification, unlike fetch.
Common mistakes with HttpClient
- Forgetting provideHttpClient(), which produces "No provider for HttpClient".
- Building a service method and never subscribing, so no request is sent.
- Concatenating unencoded user input into a URL.
Angular HttpClient— Interview Questions & FAQs
Why is my Angular HTTP request not firing?+
HttpClient returns a cold Observable — nothing happens until you subscribe, either explicitly or through the async pipe in a template.
