angular - 在 Angular 中获取先前请求的 URL
问题描述
是否可以获取以前调用的 XHR 请求 URL(使用 Angular 的 HttpClient)?
我愿意使用拦截器。怎么可能呢?指向正确的方向可能就足够了。
拥有像获取最新历史成员这样的基本功能会很酷,关于删除、清除、添加方法的基本想法也会很好。
解决方案
您可以使用拦截器来实现此目的。只需创建一个简单的拦截器:
export class XhrInterceptor implements HttpInterceptor {
constructor(private xhrHistoryService: XhrHistoryService) {}
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Here you have the information from your call and can get/store the data
this.xhrHistoryService.add(request.url);
return next.handle(request).pipe(
tap((ev: HttpEvent<any>) => {
// If you want to log responses add here
})
);
}
}
如您所见,我注入了一个 xhrHistoryService。该服务用于保存和管理历史。因为我不知道你想对你的历史做什么,这只是一个例子。如果您希望将您的历史记录用作一种缓存,您也可以直接在拦截器中执行此操作。
export class XhrHistoryService {
// Define here what types you want to log
private history: string[] = [];
public getAll() {
return this.history;
}
public getLatest() {
return this.history.length && this.history[this.history.length - 1];
}
// Define here what you want to log
public add(url: string) {
this.history.push(url);
}
}
我希望这有帮助。如果没有,请编辑您的问题以指定您的需求。
代码在这里:https ://stackblitz.com/edit/angular-ivy-atovsq?file=src/app/xhr.interceptor.ts
推荐阅读
- javascript - Razor 页面中的 DataTables 服务器端 ajax 过滤
- javascript - javascript中的setInterval函数在几秒钟后停止执行
- go - 加载工作区时出错:错误:退出状态 1:stderr:go:需要更新 go.sum,由 -mod=readonly 禁用:packages.Load 错误
- mongodb - 为什么在对 mongodb 中的现有集合进行散列分片后,数据仍在一个分片中?
- android - 在模块 core-1.5.0-runtime (androidx.core:core:1.5.0) 和 support-compat-27.1 中发现重复的类 android.support.v4.os.ResultReceiver$MyRunnable
- javascript - 执行