We use cookies to enhance your experience on the site
CodeWorlds

HttpClient in Angular - Courier Messengers

HttpClient is like a system of fast couriers (飛脚 - hikyaku) - messengers carrying messages between castles. In feudal Japan, couriers ran hundreds of kilometers delivering important information. HttpClient does the same for your application!

HttpClient Configuration

1// app.config.ts
2import { ApplicationConfig } from '@angular/core';
3import { provideHttpClient, withInterceptors, withFetch } from '@angular/common/http';
4
5export const appConfig: ApplicationConfig = {
6  providers: [
7    provideHttpClient(
8      withInterceptors([authInterceptor, loggingInterceptor]),
9      withFetch()  // Uses Fetch API instead of XMLHttpRequest
10    )
11  ]
12};

Basic HTTP Requests

1import { Injectable, inject } from '@angular/core';
2import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
3import { Observable } from 'rxjs';
4
5interface Samurai {
6  id: number;
7  name: string;
8  clan: string;
9  level: number;
10}
11
12@Injectable({ providedIn: 'root' })
13export class SamuraiService {
14  private http = inject(HttpClient);
15  private apiUrl = '/api/samurai';
16
17  // GET - fetch all
18  getAll(): Observable<Samurai[]> {
19    return this.http.get<Samurai[]>(this.apiUrl);
20  }
21
22  // GET with query parameters
23  search(query: string, clan?: string): Observable<Samurai[]> {
24    let params = new HttpParams().set('q', query);
25    if (clan) {
26      params = params.set('clan', clan);
27    }
28    return this.http.get<Samurai[]>(\`\${this.apiUrl}/search\`, { params });
29  }
30
31  // GET single
32  getById(id: number): Observable<Samurai> {
33    return this.http.get<Samurai>(\`\${this.apiUrl}/\${id}\`);
34  }
35
36  // POST - create
37  create(samurai: Omit<Samurai, 'id'>): Observable<Samurai> {
38    return this.http.post<Samurai>(this.apiUrl, samurai);
39  }
40
41  // PUT - update entire resource
42  update(id: number, samurai: Samurai): Observable<Samurai> {
43    return this.http.put<Samurai>(\`\${this.apiUrl}/\${id}\`, samurai);
44  }
45
46  // PATCH - partial update
47  partialUpdate(id: number, changes: Partial<Samurai>): Observable<Samurai> {
48    return this.http.patch<Samurai>(\`\${this.apiUrl}/\${id}\`, changes);
49  }
50
51  // DELETE - remove
52  delete(id: number): Observable<void> {
53    return this.http.delete<void>(\`\${this.apiUrl}/\${id}\`);
54  }
55}
Go to CodeWorlds