HttpClient
GET/POST、Interceptor、错误处理。
35 分钟
HttpClient
HttpClient 是 Angular 官方 HTTP 客户端,返回 RxJS Observable。与 Vue 数据获取 的 fetch + Promise 不同,Angular 项目普遍用 Observable 链式处理;对比 Next.js 核心 的服务端 fetch,Angular SPA 默认在浏览器发请求。
学习目标
- 配置
provideHttpClient()并发起 GET/POST - 用
pipe处理 map、catchError - 了解 Interceptor 统一加 Token
核心内容
启用 HttpClient
// app.config.ts
import { ApplicationConfig } from "@angular/core";
import { provideHttpClient, withInterceptors } from "@angular/common/http";
import { authInterceptor } from "./auth.interceptor";
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient(withInterceptors([authInterceptor]))],
};
GET 与错误处理
loadTracks() {
this.loading = true;
this.trackService.list().pipe(
catchError((err) => {
this.error = err.message ?? "请求失败";
return of([] as Track[]);
}),
finalize(() => (this.loading = false)),
).subscribe((tracks) => (this.tracks = tracks));
}
模板三态与 Vue 相同:loading / error / 列表。
Interceptor(概念)
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = localStorage.getItem("token");
if (token) {
req = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
}
return next(req);
};
| Angular HttpClient | Vue fetch | Next.js | |
|---|---|---|---|
| 返回 | Observable | Promise | Promise / async |
| 拦截 | Interceptor | 封装 fetch | middleware |
| 类型 | 泛型 get<T>() | 手动断言 | 同左 |
本站链路:Angular SPA → platform (Next.js) 或直连 Spring Boot /api/*。开发环境 proxy.conf.json 转发到 localhost:8080。
练习
- 对接 mock ,展示 loading 与 error UI