首页 > 解决方案 > 在 Angular 中获取先前请求的 URL

问题描述

是否可以获取以前调用的 XHR 请求 URL(使用 Angular 的 HttpClient)?

我愿意使用拦截器。怎么可能呢?指向正确的方向可能就足够了。

拥有像获取最新历史成员这样的基本功能会很酷,关于删除、清除、添加方法的基本想法也会很好。

标签: angularangular-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


推荐阅读