AI Hints
Home›Angular Tutorial›Talking to a Server, HttpClient and GET Requests
Angular · Lesson 93 of 120

GET Requests

A books service.

⏱ 2 min read▶ Video at 1:51:55🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Components shouldn't build URLs themselves. A service can keep every request to the books API, in one place.

  • No URLs in components
  • One place for requests
  • A books service

book-api.ts

The Book interface describes the data from the server. The service injects HTTP client, and keeps the base address. All gets every book. And one gets a single book, by its id.

book-api.tstypescript
import { Service, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export interface Book { id: number; title: string; author: string; price: number; }

@Service()
export class BookApi {
  private http = inject(HttpClient);
  private url = '/api/books';

  all() { return this.http.get<Book[]>(this.url); }
  one(id: number) { return this.http.get<Book>(`${this.url}/${id}`); }
}

A list and details

The component injects the books service. The constructor loads every book, into a signal. Details loads one book, by id, into picked. We click details, for Circe. Run it. The server got two requests. The list, and then book three. And the card shows Circe's details.

app.tstypescript
import { Component, inject, signal } from '@angular/core';
import { BookApi, Book } from './book-api';

@Component({
  selector: 'app-root',
  template: `
    @for (b of books(); track b.id) {
      <p>{{ b.title }} <button (click)="show(b.id)">Details</button></p>
    }
    @if (picked(); as p) { <p class="card">{{ p.title }} by {{ p.author }}</p> }
  `,
})
export class App {
  private api = inject(BookApi);
  books = signal<Book[]>([]);
  picked = signal<Book | null>(null);
  constructor() { this.api.all().subscribe(list => this.books.set(list)); }
  show(id: number) { this.api.one(id).subscribe(b => this.picked.set(b)); }
}
Output
API GET /api/books → 200
API GET /api/books/3 → 200
Also uses book-api.ts
import { Service, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export interface Book { id: number; title: string; author: string; price: number; }

@Service()
export class BookApi {
  private http = inject(HttpClient);
  private url = '/api/books';

  all() { return this.http.get<Book[]>(this.url); }
  one(id: number) { return this.http.get<Book>(`${this.url}/${id}`); }
}
Also uses actions.json
[{"click": "p:nth-of-type(3) button"}, {"wait": 600}]
Also uses _apilog
1

Summary

A service keeps the API calls, and components subscribe, and store the results in signals. Next, a closer look at observables.

Key takeaways
  • BookApi service
  • all(), one(id)
  • subscribe → signal
Next up: Observables Basics — values over time