HttpClient 是 Angular 的内置服务,用于发送 HTTP 请求。它返回 Observables(而非 Promises),与 RxJS 操作符集成,并支持类型化响应、拦截器和错误处理。
基本用法
ts
{ } ;
{ } ;
({ : })
{
() {}
() {
..<[]>();
}
() {
..<>(, user);
}
() {
..();
}
}
泛型(<User[]>)对响应进行类型化。请求是惰性的——只有在订阅时才会执行。
ngOnInit() {
this.userService.getUsers().subscribe(users => this.users = users);
}
// or with the async pipe (no manual subscribe/unsubscribe):
users$ = this.userService.getUsers();
// template: <li *ngFor="let u of users$ | async">
import { HttpParams, HttpHeaders } from "@angular/common/http";
this.http.get("/api/users", {
params: new HttpParams().set("page", "1").set("limit", "10"), // ?page=1&limit=10
headers: new HttpHeaders({ Authorization: `Bearer ${token}` }),
});
import { catchError, retry } from "rxjs/operators";
import { of } from "rxjs";
this.http.get<User[]>("/api/users").pipe(
retry(2), // retry failed requests twice
catchError(err => {
console.error(err);
return of([]); // fallback value, keep the stream alive
})
).subscribe(users => this.users = users);
由于它基于 Observable,你可以使用操作符组合重试、回退、超时和数据转换。
HTTP interceptors automatically attach auth tokens, log requests,
handle errors globally, or show loading spinners — for ALL requests.
HttpClient 是 Angular 应用与后端通信的方式——类型化、基于 Observable、并且可与 RxJS 组合用于重试/回退/转换。
其 Observable 特性(相对于 fetch 的 Promises)使其与 Angular 的其他部分集成(async 管道、操作符、拦截器)。
了解类型化请求、选项、错误处理,以及与 async 管道的配合,基本涵盖了 Angular 中几乎所有的数据获取需求。