CPCODELAB
Angular

HttpClient and Calling APIs

12 min read

Communicating with a Backend

HttpClient is Angular's built-in HTTP module. It returns Observables and supports typed responses, request/response interceptors, error handling, and progress events. Provide it using provideHttpClient() in your bootstrap configuration.

ts
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient(withFetch()),
    provideRouter(routes)
  ]
});
ts
// posts.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, catchError, throwError } from 'rxjs';

export interface Post {
  id: number;
  title: string;
  body: string;
  userId: number;
}

@Injectable({ providedIn: 'root' })
export class PostsService {
  private http = inject(HttpClient);
  private base = 'https://jsonplaceholder.typicode.com';

  getPosts(): Observable<Post[]> {
    return this.http.get<Post[]>(`${this.base}/posts`).pipe(
      catchError(err => throwError(() => new Error(err.message)))
    );
  }

  getPost(id: number): Observable<Post> {
    return this.http.get<Post>(`${this.base}/posts/${id}`);
  }

  createPost(post: Omit<Post, 'id'>): Observable<Post> {
    return this.http.post<Post>(`${this.base}/posts`, post);
  }

  deletePost(id: number): Observable<void> {
    return this.http.delete<void>(`${this.base}/posts/${id}`);
  }
}

Always type your HTTP responses with generics (get<Post[]>) to get full TypeScript inference. Use the async pipe in templates to subscribe and unsubscribe automatically, avoiding manual subscription management.

Ready to test yourself?
Practice Angular— quiz & coding exercises