1. 定制 HttpInterceptor
实现通用响应处理逻辑
- 缓存策略:
- 在
HttpInterceptor
的 intercept
方法中,创建一个缓存对象,例如 private cache: { [url: string]: any } = {};
。
- 当请求到来时,检查缓存中是否存在对应
url
的响应数据。如果存在且缓存未过期(可在缓存数据中添加时间戳字段进行判断),直接返回缓存数据,不再发起实际的 HTTP 请求。示例代码如下:
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest
} from '@angular/common/http';
import { Observable, of } from 'rxjs';
@Injectable()
export class CacheInterceptor implements HttpInterceptor {
private cache: { [url: string]: any } = {};
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (request.method === 'GET') {
const cachedResponse = this.cache[request.url];
if (cachedResponse && Date.now() - cachedResponse.timestamp < 60000) { // 假设缓存1分钟
return of(cachedResponse.response);
}
}
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse && request.method === 'GET') {
this.cache[request.url] = {
response: event,
timestamp: Date.now()
};
}
});
}
}
- 注册该拦截器到 `HttpClientModule` 的 `providers` 数组中,使其生效。
- 错误重试机制:
- 在
HttpInterceptor
的 intercept
方法中,使用 retryWhen
操作符对错误进行处理。示例代码如下:
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { retryWhen, delay, take } from 'rxjs/operators';
@Injectable()
export class RetryInterceptor implements HttpInterceptor {
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
retryWhen(errors =>
errors.pipe(
delay(1000), // 每次重试间隔1秒
take(3) // 最多重试3次
)
)
);
}
}
- 同样注册该拦截器到 `HttpClientModule` 的 `providers` 数组中。
2. 确保策略在不同网络环境和业务场景下的有效性和稳定性
- 不同网络环境:
- 网络类型检测:使用
@angular/common/http
中的 HttpEventType
来检测网络请求的状态。例如,当 HttpEventType.Sent
事件触发时,可判断请求已发出,可用于统计请求数量等。同时,利用 navigator.connection
API(在支持的浏览器中)检测网络类型(如 wifi
、cellular
等)。
- 动态调整策略:根据网络类型动态调整缓存策略和错误重试机制。例如,在
cellular
网络下,可适当缩短缓存时间以保证数据的及时性;在不稳定的网络环境下,增加错误重试次数或延长重试间隔时间。
- 不同业务场景:
- 业务场景分类:分析应用中的不同业务场景,例如数据展示场景、数据提交场景等。
- 针对性策略:
- 数据展示场景:更注重缓存策略,确保频繁请求的数据能够快速从缓存获取,减少服务器压力和用户等待时间。例如,对于首页数据展示,缓存时间可适当延长。
- 数据提交场景:更关注错误重试机制的准确性。确保数据能够成功提交,可在重试时携带更多的错误信息,以便服务器更好地处理。同时,要避免无限重试导致的资源浪费,可根据业务需求设置合理的重试次数和间隔时间。
- 可配置性:将缓存时间、重试次数等关键参数设置为可配置的,通过配置文件或服务端配置,根据不同业务场景灵活调整这些参数,以保证策略的有效性和稳定性。