Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use shareReplay for cache HTTP response with request params

I have a scenario like I need to fetch file content when click on a file. I want to cache the file content API with shareReplay(), how can I achieve it?

fileService.getContent is an API service which will fetch content with params(repository_id, filePath);

Question:

  • Where should I use the shareReplay() pipe? Inside API service? or the place I wrote below.
  • Below code does not work as expected. The API will be triggered multi-times. How can I cache the API with shareReplay() to call only once.

Component

fileOpened$ = new Subject();
...

this.fileOpened$.pipe(
    switchMap(file => this.fileService.getContent(this.repository_id, file.filePath)),
       shareReplay(1)
);

service:

getContent(repoId: string, path: string): Observable<string> {
    return this.http.get<string>(
        `/api/xxx/${repoId}/files/${decodeURIComponent(path)}`,
        {
            responseType: 'text' as 'json'
        });
}
like image 804
huan feng Avatar asked Sep 02 '25 04:09

huan feng


1 Answers

I would add the shareReplay code in the service. Because of the parameters you can create a Map that caches the Observables.

Here the stackblitz I created to demonstrate.

like image 196
Marcel Hoekstra Avatar answered Sep 05 '25 01:09

Marcel Hoekstra