HTTP
What it means
Section titled βWhat it meansβAngularβs HttpClient (from @angular/common/http) is the standard way to make HTTP requests. Every method returns an Observable, not a Promise β so requests donβt fire until you .subscribe() to them, and Angularβs async pipe can consume the result directly in a template without manual subscription management.
Examples
Section titled βExamplesβimport { HttpClient } from '@angular/common/http';import { inject } from '@angular/core';
@Injectable({ providedIn: 'root' })export class UserService { private http = inject(HttpClient);
getUser(id: string) { return this.http.get<User>(`/api/users/${id}`); // returns an Observable<User> }}
@Component({ selector: 'app-profile', template: ` @if (user$ | async; as user) { <p>{{ user.name }}</p> } `,})export class ProfileComponent { private userService = inject(UserService); user$ = this.userService.getUser('123'); // async pipe handles subscribe/unsubscribe automatically}Common mistake
Section titled βCommon mistakeβCalling an HttpClient method and never subscribing to the result β since HttpClient returns a cold Observable, the HTTP request literally never fires until something subscribes to it, which is a common source of βwhy isnβt my API call happening?β confusion.
getUser(id: string) { this.http.get<User>(`/api/users/${id}`); // does NOTHING -- no subscriber, request never sent!}
// Fix: either subscribe manually...getUser(id: string) { this.http.get<User>(`/api/users/${id}`).subscribe(user => this.user = user);}
// ...or return the Observable and let the template's async pipe subscribegetUser(id: string) { return this.http.get<User>(`/api/users/${id}`);}Quick practice
Section titled βQuick practiceβ-
Does an
HttpClientrequest fire as soon as you call.get(), or only when something subscribes?Answer
Only when something subscribes βHttpClientObservables are "cold," meaning the underlying request doesn't execute until a subscriber attaches. -
What does the
asyncpipe do in a template?Answer
Automatically subscribes to an Observable (or Promise) and unsubscribes when the component is destroyed, so you don't have to manage subscriptions manually. -
What type does every
HttpClientmethod (like.get(),.post()) return?Answer
AnObservable, not a Promise β you can stillawait firstValueFrom(...)to convert it if a Promise-based API is more convenient in a given spot.