在 Angular 中获取先前请求的 URL

Fetch previously requested URL in Angular

是否可以获取之前调用的 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