管理系统通常有多个业务模块调用同一套 HTTP 接口。如果每个组件分别设置请求头、统计加载状态和处理错误,网络逻辑会逐渐分散。Angular HttpClient 的函数式拦截器可以集中处理横切职责,而 HttpContext 则可以为单个请求传递不需要发送给服务器的策略。本文围绕请求追踪、加载指示、有限重试以及权限错误处理建立清晰的网络层边界。
下列代码块按各节独立展示,实际接入时应结合相应的样式、脚本或组件文件。
1. 建立网络层与组件的职责边界
组件只关心加载结果与业务错误,不应依赖某个拦截器内部的状态变量。拦截器适合处理请求级公共行为;例如为内部 API 增加请求头,不能把所有响应结构强行改造成同一种格式。下面的模板表示库存读取场景。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/f200d8339bffbdc1bbf2701d37d5331d490f24ab">
<section class="inventory-panel"><h2>库存管理</h2><button type="button" (click)="reload()">刷新</button><p role="status">{
{ status() }}</p></section>
</div>
import {
HttpClient } from '@angular/common/http';
import {
inject, Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' })
export class InventoryApi {
private readonly http = inject(HttpClient);
list() {
return this.http.get<unknown>('/api/inventory'); }
}
2. 注册函数式拦截器
独立启动配置中通过 provideHttpClient 和 withInterceptors 指定执行链。注册顺序影响请求处理顺序,也影响响应返回时的嵌套顺序。以下代码假定 requestTrace 和 loadingInterceptor 是已经定义好的函数式拦截器。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/2e6f65d0dd4013766bbf6058b7f840329f3ffb02">
<main class="app-shell"><header>业务系统</header><router-outlet></router-outlet></main>
</div>
import {
bootstrapApplication } from '@angular/platform-browser';
import {
provideHttpClient, withInterceptors } from '@angular/common/http';
import {
App } from './app';
import {
requestTrace, loadingInterceptor } from './interceptors';
bootstrapApplication(App, {
providers: [provideHttpClient(withInterceptors([requestTrace, loadingInterceptor]))] });
3. 通过 clone 创建修改后的请求
HttpRequest 的常用配置采用不可变模式,修改请求头时应调用 clone,而不是直接赋值。示例只给应用约定的相对 API 路径添加追踪头,并保留调用方已经提供的追踪标识。该标识用于诊断,不代表业务幂等键。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/3771b3b79e40ed7d709371ccd07c25a551db2db8">
<section class="request-detail"><h2>请求诊断</h2><dl><dt>请求标识</dt><dd>由应用网络层生成</dd></dl></section>
</div>
import {
HttpInterceptorFn } from '@angular/common/http';
export const requestTrace: HttpInterceptorFn = (req, next) => {
if (!req.url.startsWith('/api/') || req.headers.has('X-Request-ID')) return next(req);
return next(req.clone({
setHeaders: {
'X-Request-ID': crypto.randomUUID() } }));
};
4. 通过 HttpContext 声明静默请求
后台定时同步不一定需要显示全局加载遮罩。使用 HttpContextToken 定义策略,调用方按需设置。它与 HTTP 请求头不同,不会直接作为网络字段发送。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/14c614a55eeb393861f2bd9f11ed2e369dc47b43">
<aside class="sync-indicator"><p role="status">后台同步不阻塞当前操作。</p></aside>
</div>
import {
HttpContext, HttpContextToken, HttpClient } from '@angular/common/http';
export const SILENT_REQUEST = new HttpContextToken<boolean>(() => false);
export function refreshSilently(http: HttpClient) {
return http.get<unknown>('/api/inventory', {
context: new HttpContext().set(SILENT_REQUEST, true) });
}
5. 并发加载采用计数而非布尔值
多个请求同时进行时,第一个完成不能让全局 loading 直接归零。通过计数维护活动请求数量,并在 finalize 中处理完成、错误和取消。该示例用 defer 确保每次实际订阅都独立增加计数。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/35cd1547a7cf0e7e54d4c946272cfaec75538f9a">
<section class="network-status" aria-live="polite"><p>进行中的请求:{
{ tracker.active() }}</p></section>
</div>
import {
inject, Injectable, signal } from '@angular/core';
import {
HttpInterceptorFn } from '@angular/common/http';
import {
defer, finalize } from 'rxjs';
import {
SILENT_REQUEST } from './request-context';
@Injectable({
providedIn: 'root' })
export class LoadingTracker {
private readonly count = signal(0);
readonly active = this.count.asReadonly();
begin() {
this.count.update(n => n + 1); }
end() {
this.count.update(n => n - 1); }
}
export const loadingInterceptor: HttpInterceptorFn = (req, next) => {
const tracker = inject(LoadingTracker);
if (req.context.get(SILENT_REQUEST)) return next(req);
return defer(() => {
tracker.begin();
return defer(() => next(req)).pipe(finalize(() => tracker.end()));
});
};
6. 错误映射不应吞掉原始失败
catchError 可以把 HTTP 错误转换为更明确的应用错误,但若返回一个虚构的空列表,就可能让调用方把失败误判为库存为零。拦截器可以记录或分类,最终仍让组件收到失败。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/0d0986a75b9221d2886d09123922ea7659736438">
<section class="request-error"><p role="alert">读取库存失败,请稍后重试。</p><button type="button" (click)="reload()">重试</button></section>
</div>
import {
HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import {
catchError, throwError } from 'rxjs';
export const errorInterceptor: HttpInterceptorFn = (req, next) => next(req).pipe(
catchError((error: unknown) => {
if (error instanceof HttpErrorResponse) console.debug('HTTP failure', error.status);
return throwError(() => error);
})
);
7. 限制自动重试的请求范围
读取请求和写入请求的风险不同。以下示例仅对 GET 的暂时性错误启用有限重试,且只适用于业务确认可以重复读取的接口。对 429 应按服务端 Retry-After 等约束设计独立策略,不应简单提高重试频率。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/6b704478e0db7d11659844d36dd864f443885ef2">
<section class="read-recovery"><h2>库存读取恢复</h2><p>短暂连接故障时可重新读取库存,不自动重复提交订单。</p></section>
</div>
import {
HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import {
retry, throwError, timer } from 'rxjs';
export const readRetry: HttpInterceptorFn = (req, next) => {
if (req.method !== 'GET' || !req.url.startsWith('/api/inventory')) return next(req);
return next(req).pipe(retry({
count: 2, delay: (error, attempt) => {
if (error instanceof HttpErrorResponse && [0, 502, 503, 504].includes(error.status)) return timer(250 * 2 ** (attempt - 1));
return throwError(() => error);
} }));
};
8. 认证状态与请求重试分离
401 表示当前请求缺少有效认证信息或认证已失效等情况,403 则可能是权限不足。不要对所有错误循环刷新 Token。若应用使用刷新机制,应避免刷新请求本身再次进入刷新流程,并对并发刷新做合并;Cookie 会话还需要独立处理 CSRF 防护。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a0b72e92a66a0430564de512a3a06595008bf2cf">
<section class="auth-notice"><h2>会话需要确认</h2><p>当前操作未获得有效认证。</p><button type="button" (click)="signIn()">重新登录</button></section>
</div>
import {
HttpErrorResponse } from '@angular/common/http';
export function classifyHttpError(error: unknown): string {
if (!(error instanceof HttpErrorResponse)) return 'unknown';
if (error.status === 401) return 'authentication';
if (error.status === 403) return 'forbidden';
if (error.status === 0) return 'transport';
return 'http';
}
9. 组件卸载时取消订阅
对不再需要的请求,应结束对应订阅。takeUntilDestroyed 可将订阅与组件生命周期绑定;取消订阅可以中止尚未完成的客户端 HTTP 请求,但不能保证已经到达服务端的写入操作被撤销。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/9968e81dcb63c3d5b02eeafcc6bb7543f8892c68">
<section class="inventory-summary"><h2>库存摘要</h2><p>离开页面时释放当前读取操作。</p></section>
</div>
import {
Component, DestroyRef, inject } from '@angular/core';
import {
takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
InventoryApi } from './inventory-api';
@Component({
selector: 'app-inventory-summary', template: '<h2>库存摘要</h2>' })
export class InventorySummary {
private readonly api = inject(InventoryApi);
private readonly destroyRef = inject(DestroyRef);
load() {
this.api.list().pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
next: data => console.debug('received inventory', Array.isArray(data)), error: () => console.debug('load failed') }); }
}
10. 针对拦截器链编写可重复的测试
使用 HttpTestingController 验证请求头、静默策略以及错误传播。测试提供者应先注册正常 HttpClient 再注册测试后端。测试中不应该真实调用线上 API,也不应把测试成功误认为部署环境已经完成验证。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a5d37d9a44d7b56c061d41212d31f619d55f8f63">
<section class="http-test-cases"><h2>网络层验证</h2><ul><li>内部请求包含追踪标识</li><li>外部资源请求不增加内部请求头</li><li>失败与取消后加载计数恢复</li></ul></section>
</div>
import {
TestBed } from '@angular/core/testing';
import {
HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import {
HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import {
requestTrace } from './interceptors';
export function checkTraceInterceptor(): void {
TestBed.configureTestingModule({
providers: [provideHttpClient(withInterceptors([requestTrace])), provideHttpClientTesting()] });
const http = TestBed.inject(HttpClient);
const mock = TestBed.inject(HttpTestingController);
http.get('/api/inventory').subscribe();
const req = mock.expectOne('/api/inventory');
if (!req.request.headers.has('X-Request-ID')) throw new Error('missing trace header');
req.flush([]);
mock.verify();
}
总结
拦截器适合集中处理网络横切逻辑,但不能变成所有业务规则的存放位置。保持请求策略显式、错误不被吞掉、加载计数与订阅生命周期对称,并严格区分可安全重试的读取与有副作用的写入请求,才能构建可预测的 Angular 网络层。