# Angular HTTP Client --- #### Overview  --- #### Requests ```typescript http.get
(`/api/students/${id}`).subscribe(student => { // process student }); ``` ```json { "id": 42, "name": "John Doe", "data": "unused" } ``` ```typescript export interface Student { id: number, name: string } ```
Generisch
Lazy requests (
subscribe
)
---- #### Post ```typescript http.post(url, body) ``` ```typescript http.post
('/api/students', newStudent) .subscribe(student => { console.log('Student saved:', student); }); ``` ---- #### Query params ```typescript go(): Student[] { return http.get
('/api/search', { params: {q: 'angular'}, // /api/search?q=angular }); } ``` Kein Request geht raus; warum? --- #### Headers ```typescript http.get
('/api/status', { headers: { 'Authorization': 'Basic bG9yZW0gaXBzdW0=' } } ); ``` Zugriff auf Response header: ```typescript http.get
('/api/status', { observe: 'response' }) .subscribe(res => { console.log('Response status:', res.status); console.log('Body:', res.body); }); ``` --- #### Service ```typescript export class ApiService { private readonly baseUrl = 'http://www.the-backend.com/api'; constructor(private readonly http: HttpClient) { } getAllStudent() { return this.http .get
(`${this.baseUrl}/students`); } saveStudent() { return this.http .post
(`${this.baseUrl}/students`); } } ``` ---- #### Error handling ```typescript StudentListComponent { students = signal
([]); error = signal(''); constructor(private apiService: ApiService) { apiService.getAllStudents() .subscribe({ next: students => this.students.set(students), error: error => this.error.set(error) }); } } ``` ---- #### Caching ```typescript export class ApiService { private readonly baseUrl = environment.baseUrl; private readonly _students = signal
([]); readonly students = this._students.asReadonly(); getStudent(id: number): Observable
{ const cached = this._students().find(p => p.id === id) if (cached) return of(cached); // cache miss return this.http .get
(`${this.baseUrl}/students/${id}`) .pipe( tap(student => this._students.set([...this._students(), student])) ); } ``` --- #### `| async` ```angular181html @for (student of students$ | async; track $index) {
} ``` ```typescript Component { students$: Observable
; constructor(private apiService: ApiService) { this.students$ = apiService.getAll(); } } ``` automatisches `subscribe` --- #### Interceptors ```typescript getAllStudents() { console.log('Request:', 'GET', `${this.baseUrl}/students`); return this.http .get
(`${this.baseUrl}/students`) .pipe(tap(res => console.log('Response:', res))); } saveStudent(student: Student) { console.log('Request:', 'POST', `${this.baseUrl}/students`); return this.http .post
(`${this.baseUrl}/students`, student) .pipe(tap(res => console.log('Response:', res))); } ... ``` Funktionalität dupliziert auf alle http-Calls ---- #### Interceptors ```typescript export const logInterceptor: HttpInterceptorFn = (req, next) => { console.log('Request:', req.method, req.url); return next(req).pipe(tap(res => console.log('Response:', res))); }; ``` ```typescript export const appConfig: ApplicationConfig = { providers: [provideHttpClient(withInterceptors( [errorInterceptor, logInterceptor]))] }; ``` ---- #### Use cases * Authentication Header * Failed Requests retrying * Caching * Logging * Zeitmessung bis zur Serverantwort