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

HttpClient

Angular talks HTTP.

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

Angular has a service for HTTP, called HTTP client. Our course's lesson server has a small books API, at slash api slash books.

  • A service for HTTP
  • HttpClient
  • A books API to try

app.config.ts

The app config sets up the whole app. Provide HTTP client makes the HTTP client service available. With fetch tells it to use the browser's fetch function.

app.config.tstypescript
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes, withComponentInputBinding()),
    provideHttpClient(withFetch()),
  ]
};

A first request

We inject HTTP client. Get sends a get request, and the type says what we expect back. Subscribe sends it, and receives the books. We log the first title, and store the count. Run it. The server logged a get request, with status two hundred. The first book is Dune, and the page shows four books.

app.tstypescript
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  template: `<p>Books from the server: {{ count() }}</p>`,
})
export class App {
  private http = inject(HttpClient);
  count = signal(0);

  constructor() {
    this.http.get<{ title: string }[]>('/api/books').subscribe(books => {
      console.log('First book:', books[0].title);
      this.count.set(books.length);
    });
  }
}
Output
API GET /api/books → 200
First book: Dune
Also uses _apilog
1

What happened

Get returned an observable, a value that arrives later. Subscribe started the request. When the response came, our function ran, with the books. Everything else on the page kept working while we waited.

keyvalue
http.get<T>(url)returns an observable
.subscribe(fn)sends the request
fn(books)runs when it arrives
Meanwhilethe page keeps working

Summary

Inject HTTP client, call get with the type you expect, and subscribe to send it. Next, GET requests in a service.

Key takeaways
  • provideHttpClient()
  • http.get<T>()
  • subscribe()
Next up: GET Requests — a books service